IOC(控制反轉/依賴注入)透過抽象介面隔離使用者與具體實現,但最終仍需建立具體實例。為消除建立依賴,將依賴移至外部配置。三種注入形式:建構子注入、設值注入、介面注入。
Windsor 是 Castle 的 IOC 容器,構建於 MicroKernel 之上,功能強大:自動檢測類別所需參數、分析類別間依賴、提供服務與錯誤預警機制。
public interface ILog { void Write(string msgStr); }
public interface ILogFormatter { string Format(string msgStr); }
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 + "]";
}
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<components>
<component id="txtLog">
<parameters><target>log.txt</target></parameters>
</component>
</components>
</configuration>
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
ILog、ILogFormatter,實現可任意替換。TextFileLog、TextFormatter。TextFileLog 依賴 ILogFormatter),無需 XML 手工配置依賴關係。全程零 new 關鍵字,代碼優雅簡潔。後續將深入講解 Castle IOC 及其 Facilities。