歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> 談談對.NET開源框架Castle的認識

談談對.NET開源框架Castle的認識

日期:2017/3/1 9:31:49   编辑:Linux編程

最近項目優化,由架構師溫工手把手輔導我搭架構,能每天接受一位久經沙場架構師的親自指導,對我是莫大的榮幸。

架構分為三個模塊:AlarmEngineCoreLib模塊為接口模塊,AlarmEngineKernalLib模塊為具體實現類模塊,AlarmEngineWebApp為對外發布的WCF模塊。核心模塊AlarmEngineWebApp目錄如下:

我們在AlarmEngineWebApp模塊通過Castle管理AlarmEngineCoreLib接口和AlarmEngineKernalLib實現類的關系。

配置過程如下:

1.在配置文件配置接口和實現類的關系:

<?xml version="1.0"?>
<configuration>
<configSections>
<section name="castle" type="Castle.Windsor.Configuration.AppDomain.CastleSectionHandler,Castle.Windsor"/>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
</configSections>
<castle>
<components>
<component id="log_service" service="AlarmEngineCoreLib.IService" type="AlarmEngineKernalLib.LogService,AlarmEngineKernalLib"/>
<component id="data_source_service" service="AlarmEngineCoreLib.IService" type="AlarmEngineKernalLib.DataSourceService,AlarmEngineKernalLib"/>
<component id="write_to_db_service" service="AlarmEngineCoreLib.IService" type="AlarmEngineKernalLib.WriteToDBService,AlarmEngineKernalLib"/>
<component id="rule_engine_service" service="AlarmEngineCoreLib.IService" type="AlarmEngineKernalLib.RuleEngine,AlarmEngineKernalLib"/>
<component id="memory_pool_service" service="AlarmEngineCoreLib.IService" type="AlarmEngineKernalLib.MemeryPool,AlarmEngineKernalLib"/>
</components>
</castle>
</configuration>

2.在代理類(靜態代理)中聲明目標接口,通過一個對外的方法CreateMemoryPool控制接口的實現過程。

using System;
using AlarmEngineCoreLib;

namespace AlarmEngineWebApp
{
public class MemoryPoolProxyService : IMemoryPoolProxyService
{
private static IMemoryPool memoryPool = null;

/// <summary>
/// 提供對外創建具體類的方法
/// </summary>
public static void CreateMemoryPool(IServiceContainer _Container)
{
MemoryPoolProxyService.memoryPool = _Container.GetService("AlarmEngineKernalLib.MemeryPool") as IMemoryPool;
}
}
}

3.在Global啟動時,調用代理類的對外方法,完成接口的實現過程。

/// <summary>
/// 報警引擎服務容器
/// </summary>
public static Global _AlarmEngineApp = null;

void Application_Start(object sender, EventArgs e)
{
// 在應用程序啟動時運行的代碼
_AlarmEngineApp = new Global();

MemoryPoolProxyService.CreateMemoryPool(_AlarmEngineApp);
}

這樣,我們通過Castle提供的容器管理接口和實現類之間的關系,典型的依賴注入容器。

Castle是針對.NET平台下的一個非常優秀的開源項目,從數據訪問框架 ORM到依賴注入容器,再到WEB層的MVC框架、AOP,基本包括了整個開發過程中的所有東西,為我們快速的構建企業級的應用程序提供了很好的服務。

Castle功能很強大,我們這個架構只是用到了冰山一角,其他功能還需繼續研究。

Copyright © Linux教程網 All Rights Reserved