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

Castle Windsor 實戰:將 IoC 容器整合進專案實現依賴注入

     編輯:關於.NET

專案級容器封裝設計

在實際專案中,建議將容器初始化、組件註冊、解析介面封裝為**單例工具類別**,避免重複建立容器並統一異常處理。

Container 單例封裝類別

public sealed class Container
{
    private readonly WindsorContainer _windsor;
    private readonly IKernel _kernel;

    public IKernel Kernel => _kernel;

    private static readonly Container _instance = new Container();
    public static Container Instance => _instance;

    private Container()
    {
        try
        {
            // 從 App.config/Web.config 的  區段載入組件註冊
            var source = new Castle.Core.Resource.ConfigResource();
            var interpreter = new XmlInterpreter(source);
            _windsor = new WindsorContainer(interpreter);
            _kernel = _windsor.Kernel;
        }
        catch (Exception ex)
        {
            // 專案自訂異常處理
            TMSExcetionBase.ProcessBizException(ex);
        }
    }

    /// 依服務型別解析
    public T Resolve() => (T)_kernel[typeof(T)];

    /// 依服務名稱解析
    private object Resolve(string key) => _kernel[key];

    public void Dispose() => _kernel.Dispose();
}

App.config 組態結構:模組化 include 機制

主組態僅引用子組態檔,達成模組解耦:

<configuration>
  <configSections>
    <section name="castle" type="Castle.Windsor.Configuration.AppDomain.CastleSectionHandler, Castle.Windsor" />
  </configSections>
  <castle>
    <include uri="file://Configuration/TMS.Role.config" />
    <include uri="file://Configuration/TMS.UserInfo.config" />
  </castle>
</configuration>

子組態檔範例:TMS.UserInfo.config

<configuration>
  <components>
    <component id="UserInfo"
               service="TMS.Service.IUserInfoService,TMS.Service"
               type="TMS.Component.UserInfoComponent,TMS.Component" />
  </components>
</configuration>
  • service:介面完整型別名稱(含組件名)。
  • type:實作類別完整型別名稱。
  • 容器啟動時自動掃描 include 指定的檔案並註冊。

在 ASP.NET WebForm 中使用

public partial class UserList : System.Web.UI.Page
{
    // 欄位注入或屬性注入皆可,這裡示範手動解析
    private IUserInfoService _userService = Container.Instance.Resolve();

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            GridView1.DataSource = _userService.InquireAll();
            GridView1.DataBind();
        }
    }
}

執行結果:GridView 正常顯示資料,證明容器成功解析 IUserInfoService 並注入實作 UserInfoComponent。

關鍵優勢

  1. 單例容器:應用程式域內僅一個 WindsorContainer,效能最佳。
  2. 組態外部化:新增/修改服務實作零程式碼變更,僅增減 .config 檔。
  3. 模組化 include:依功能模組拆分組態,團隊並行開發無衝突。
  4. 統一異常處理:建構子統一 try-catch,避免啟動期例外未處理。

進階提示

  • 生產環境建議搭配 PerWebRequest 或 Transient 生命週期管理。
  • 可擴充 Container 加入 Register 方法支援程式碼式註冊(Fluent API)。
  • 整合 ASP.NET MVC 時,實作 IControllerFactory 交由 Windsor 建構 Controller。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved