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 }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值