天天看點

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

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

   架構分為三個子產品:AlarmEngineCoreLib子產品為接口子產品,AlarmEngineKernalLib子產品為具體實作類子產品,AlarmEngineWebApp為對外釋出的WCF子產品。核心子產品AlarmEngineWebApp目錄如下:

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

   我們在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功能很強大,我們這個架構隻是用到了冰山一角,其他功能還需繼續研究。

繼續閱讀