Unity Constructor Dependency Injection

Unity的构造函数依赖注入提供一种默认的行为,在Resolve一个类型实例时完成依赖注入(这个类型并不一定需要注册,但注入类型需要注册)。看一个简单的示例:

 1 public interface IMyInterface
 2 {
 3 
 4 }
 5 
 6 public interface IMyInterface2
 7 {
 8 
 9 }
10 
11 public sealed class MyInterfaceImpl : IMyInterface
12 {
13 
14 }
15 
16 public sealed class MyInterface2Impl : IMyInterface2
17 {
18 
19 }
20 
21 public sealed class MyObject
22 {
23   public MyObject(IMyInterface myInterface, IMyInterface2 myInterface2)
24   {
25 
26   }
27 }
28 
29 IUnityContainer unityContainer = new UnityContainer();
30 
31 unityContainer.RegisterType<IMyInterface, MyInterfaceImpl>();
32 unityContainer.RegisterType<IMyInterface2, MyInterface2Impl>();
33 
34 MyObject myObject = unityContainer.Resolve<MyObject>();

MyObject的构造函数参数myInterface和myInterface2被注入了MyInterfaceImpl和MyInterface2Impl。如果需要注入特定的类型,可以通过DependencyAttribute指定注册名称。

1 public sealed class MyObject
2 {
3   public MyObject([Dependency("MyInterface")]IMyInterface myInterface, IMyInterface2 myInterface2)
4   {
5 
6   }
7 }

当一个类型定义了多个构造函数时,可以通过InjectionConstructorAttribute声明被注入的构造函数。

 1 public sealed class MyObject
 2 {
 3   public MyObject(IMyInterface myInterface)
 4   {
 5 
 6   }
 7 
 8   [InjectionConstructor]
 9   public MyObject(IMyInterface myInterface, IMyInterface2 myInterface2)
10   {
11 
12   }
13 }
posted @ 2012-08-10 11:27  junchu25  阅读(354)  评论(0编辑  收藏  举报