控制反轉將依賴對象創建移交外部容器,實現鬆耦合。本文介紹 IoC 四大核心概念(型別匹配、建構子/屬性/方法注入),並以 Unity 容器完整示範四種注入方式的配置與程式碼驗證。
[Dependency])[InjectionMethod])介面與實作:
public interface IA {} public interface IB {} public interface IC {} public interface ID {}
public class A : IA
{
public IB B { get; set; }
[Dependency] public IC C { get; set; }
public ID D { get; set; }
public A(IB b) { this.B = b; } // 建構子注入 B
[InjectionMethod]
public void Initialize(ID d) { this.D = d; } // 方法注入 D
}
public class B : IB {} public class C : IC {} public class D : ID {}
設定檔註冊型別映射:
<unity>
<container name="defaultContainer">
<register type="UnityDemo.IA, UnityDemo" mapTo="UnityDemo.A, UnityDemo"/>
<register type="UnityDemo.IB, UnityDemo" mapTo="UnityDemo.B, UnityDemo"/>
<register type="UnityDemo.IC, UnityDemo" mapTo="UnityDemo.C, UnityDemo"/>
<register type="UnityDemo.ID, UnityDemo" mapTo="UnityDemo.D, UnityDemo"/>
</container>
</unity>
解析驗證:
var container = new UnityContainer();
var config = ConfigurationManager.GetSection("unity") as UnityConfigurationSection;
config.Configure(container, "defaultContainer");
var a = container.Resolve<IA>() as A;
Console.WriteLine("a.B == null ? " + (a.B == null ? "Yes" : "No")); // No
Console.WriteLine("a.C == null ? " + (a.C == null ? "Yes" : "No")); // No
Console.WriteLine("a.D == null ? " + (a.D == null ? "Yes" : "No")); // No
輸出全為 No,證明四種注入均生效:IA→A(型別匹配)、IB→B(建構子)、IC→C(屬性)、ID→D(方法)。
[Dependency] | 屬性注入 | 可選依賴、循環依賴打破 |
| [InjectionMethod] | 方法注入 | 複雜初始化邏輯、多參數注入 |
理解 IoC 核心機制是掌握 MVC ControllerActivator/DependencyResolver 整合的基礎。