IOC:英文全称:Inversion of Control,中文名称:控制反转,它还有个名字叫依赖注入(Dependency Injection)。
作用:将各层的对象以松耦合的方式组织在一起,解耦,各层对象的调用完全面向接口。当系统重构的时候,代码的改写量将大大减少。
理解依赖注入:
引入Unity:http://unity.codeplex.com/
或者VS GuGet中引用
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;
}
[InjectionMethod]
public void Initialize(ID d)
{
this.D = d;
}
}
public class B : IB { }
public class C : IC { }
public class D : ID { }
代码方式注册:
static void Main(string[] args)
{
// http://unity.codeplex.com/ IUnityContainer container = new UnityContainer(); //注册映射
container.RegisterType<IA, A>();
container.RegisterType<IB, B>();
container.RegisterType<IC, C>();
container.RegisterType<ID, D>(); //得到A的实例
A a = (A)container.Resolve<IA>(); Console.WriteLine("a.B == null ? {0}", a.B == null ? "Yes" : "No");
Console.WriteLine("a.C == null ? {0}", a.C == null ? "Yes" : "No");
Console.WriteLine("a.D == null ? {0}", a.D == null ? "Yes" : "No"); Console.Read();
}
配置文件方式注册:
<configuration>
<configSections>
<section name="unity"
type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection,Microsoft.Practices.Unity.Configuration"/>
</configSections>
<unity>
<containers>
<container>
<register type="Client.IA, Client" mapTo="Client.A, Client"/>
<register type="Client.IB, Client" mapTo="Client.B, Client"/>
<register type="Client.IC, Client" mapTo="Client.C, Client"/>
<register type="Client.ID, Client" mapTo="Client.D, Client"/>
</container>
</containers>
</unity> </configuration>
static void Main(string[] args)
{
// http://unity.codeplex.com/
IUnityContainer container = new UnityContainer();
UnityConfigurationSection configuration = (UnityConfigurationSection)ConfigurationManager.GetSection(UnityConfigurationSection.SectionName);
configuration.Configure(container);
A a = (A)container.Resolve<IA>(); Console.WriteLine("a.B == null ? {0}", a.B == null ? "Yes" : "No");
Console.WriteLine("a.C == null ? {0}", a.C == null ? "Yes" : "No");
Console.WriteLine("a.D == null ? {0}", a.D == null ? "Yes" : "No"); Console.Read();
}