首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> 關於.NET

Castle IOC 容器內幕故事(上)

     編輯:關於.NET

核心架構三層剖析

  1. WindsorContainer 分析
  2. MicroKernel 分析
  3. 組件註冊流程

一、WindsorContainer:門面模式封裝

WindsorContainer 是 Castle 的 IOC 容器,構建於 MicroKernel 之上:

Castle架構圖

圖1:WindsorContainer 位於 MicroKernel 之上

WindsorContainer封裝關係

圖2:WindsorContainer 封裝 MicroKernel 並提供擴展點

MicroKernel 輕量、僅依賴 Castle.Model,擴展性極強。WindsorContainer 提供門面,核心仍是 MicroKernel。

二、MicroKernel 核心結構

MicroKernel結構

圖3:MicroKernel 三大核心組成

  • SubSystems:擴展功能(配置、型別轉換等),可自訂
  • Components:組件 = 實現服務介面的可重用程式單元
  • Facilities:擴充單元,以外掛形式擴展容器功能(事件訂閱、屬性附加、攔截器、生命週期控制等)

三、組件註冊流程深度追蹤

WindsorContainer 只是委派給 MicroKernel:

public virtual void AddComponent(string key, Type classType)
{
    _kernel.AddComponent(key, classType);
}
public virtual void AddComponent(string key, Type serviceType, Type classType)
{
    _kernel.AddComponent(key, serviceType, classType);
}

MicroKernel AddComponent 核心步驟:

public virtual void AddComponent(string key, Type classType)
{
    // 參數驗證
    ComponentModel model = ComponentModelBuilder.BuildModel(key, classType, classType, null);
    RaiseComponentModelCreated(model);
    IHandler handler = HandlerFactory.Create(model);
    RegisterHandler(key, handler);
}

1. 建立 ComponentModel(元資料庫)

public ComponentModel BuildModel(string key, Type service, Type classType, IDictionary extendedProperties)
{
    ComponentModel model = new ComponentModel(key, service, classType);
    if (extendedProperties != null) model.ExtendedProperties = extendedProperties;
    foreach (IContributeComponentModelConstruction contributor in contributors)
        contributor.ProcessModel(kernel, model);
    return model;
}

依序調用八大 Contributors 處理配置、生命週期、建構函數依賴、屬性依賴等。

2. 觸發 ComponentModelCreated 事件

protected virtual void RaiseComponentModelCreated(ComponentModel model)
{
    ComponentModelDelegate eventDelegate = (ComponentModelDelegate)events[ComponentModelCreatedEvent];
    if (eventDelegate != null) eventDelegate(model);
}

3. 建立 Handler(不直接建構組件,負責建立 Activator)

public virtual IHandler Create(ComponentModel model)
{
    IHandler handler = new DefaultHandler(model);
    handler.Init(kernel);
    return handler;
}

4. 註冊 Handler,觸發 ComponentRegistered/HandlerRegistered 事件

完成整個組件註冊流程。後續文章將詳細剖析 Contributors、Handlers、Activator 等核心角色。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved