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

Castle IOC 容器快速入門指南

     編輯:關於.NET

為什麼需要 IOC?

IOC(控制反轉/依賴注入)透過抽象介面隔離使用者與具體實現,但最終仍需建立具體實例。為消除建立依賴,將依賴移至外部配置。三種注入形式:建構子注入、設值注入、介面注入。

什麼是 Castle IOC 容器?

Windsor 是 Castle 的 IOC 容器,構建於 MicroKernel 之上,功能強大:自動檢測類別所需參數、分析類別間依賴、提供服務與錯誤預警機制。

快速入門範例:日誌組件

1. 新增專案並引用四大核心組件

  • Castle.DynamicProxy.dll
  • Castle.MicroKernel.dll
  • Castle.Model.dll
  • Castle.Windsor.dll

2. 定義服務介面


public interface ILog { void Write(string msgStr); }
public interface ILogFormatter { string Format(string msgStr); }

3. 實作組件


public class TextFileLog : ILog
{
    private string _target; private ILogFormatter _format;
    public TextFileLog(string target, ILogFormatter format)
    { _target = target; _format = format; }
    public void Write(string msgStr)
    {
        string formatted = _format.Format(msgStr) + _target;
        Console.WriteLine("Output " + formatted);
    }
}

public class TextFormatter : ILogFormatter
{
    public string Format(string msgStr) => "[" + msgStr + "]";
}

4. 配置檔(指定建構函數額外參數 target)


<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <components>
    <component id="txtLog">
      <parameters><target>log.txt</target></parameters>
    </component>
  </components>
</configuration>

5. 使用容器


public class App
{
    public static void Main()
    {
        // 建立容器
        IWindsorContainer container = new WindsorContainer(new XmlInterpreter("../../BasicUsage.xml"));
        // 註冊組件
        container.AddComponent("txtLog", typeof(ILog), typeof(TextFileLog));
        container.AddComponent("format", typeof(ILogFormatter), typeof(TextFormatter));
        // 解析使用
        ILog log = (ILog)container["txtLog"];
        log.Write("First Castle IOC Demo");
        Console.ReadLine();
    }
}

輸出:Output [First Castle IOC Demo]log.txt

四大核心概念

  1. 服務:介面約定,如 ILog、ILogFormatter,實現可任意替換。
  2. 組件:實現服務介面的類別,如 TextFileLog、TextFormatter。
  3. 自動裝配:容器自動管理組件依賴(如 TextFileLog 依賴 ILogFormatter),無需 XML 手工配置依賴關係。

全程零 new 關鍵字,代碼優雅簡潔。後續將深入講解 Castle IOC 及其 Facilities。

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