一、首先我们了解IOC如何注入的几种姿势
- 构造函数注入(Constructor Injection)
Ioc容器会智能的选择和调用合适的构造函数以创建依赖的对象。如果被选择的构造函数具有相应的参数,Ioc容器在调用构造函数之前解析注册的依赖关系并自行初始化获得相应的参数对象。
- 属性注入(Property Injection)
通过[Dependency]标记为依赖属性,在创建对象时,依赖属性对象会被IOC容器自行获取相应的对象。
- 方法注入(Method Injection)
通过[InjectionMethod]标记此方法为依赖方法,此方法会自动被调用,方法所需参数IOC会自动获取。
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.Practices.Unity; namespace MyIoc { public interface IA{} public interface IB{} public interface IC{} public interface ID{} public interface IE{} public class A : IA { public IB B { get; set; } [Dependency] public IC C { get; set; } public ID D { get; set; } public IE E { get; set; } public A(IB b) { this.B = b; } [InjectionMethod] public void Initialize(ID d) { this.D = d; Console.WriteLine("初始化方法正在调用"); } } public class B : IB{} public class C : IC{} public class D : ID{} public class E : IE{} }
static void Main(string[] args) { IUnityContainer container = new UnityContainer(); UnityConfigurationSection configuration = ConfigurationManager.GetSection(UnityConfigurationSection.SectionName) as UnityConfigurationSection; configuration.Configure(container, "defaultContainer"); var a = container.Resolve<IA>() as A; Console.WriteLine("B(构造函数注入)是否有值:{0}",a.B==null?"没有":"有"); Console.WriteLine("C(属性注入)是否有值:{0}", a.C == null ? "没有" : "有"); Console.WriteLine("D(方法注入)是否有值:{0}", a.D == null ? "没有" : "有"); Console.Read(); }
运行结果: