Unity的属性依赖注入不同于构造函数的默认注入,它需要显示为被注入的属性添加DependencyAttribute。
1 public sealed class MyObject 2 { 3 public MyObject() { } 4 5 [Dependency] 6 public IMyInterface MyInterface { get; set; } 7 8 public IMyInterface2 MyInterface2 { get; set; } 9 }10 11 IUnityContainer unityContainer = new UnityContainer();12 13 unityContainer.RegisterType();14 unityContainer.RegisterType ();15 16 MyObject myObject = unityContainer.Resolve ();
MyObject的MyInterface属性被注入了MyInterfaceImpl,但是MyInterface2属性由于没有DependencyAttribute则不被注入。Unity还提供了OptionalDependencyAttribute,当某个属性依赖的类型没有被注册或者注入失败时,属性的值为null。
1 public sealed class MyObject2 {3 [OptionalDependency]4 public IMyInterface MyInterface { get; set; }5 6 [Dependency]7 public IMyInterface2 MyInterface2 { get; set; }8 }
如果IMyInterface2没有被注册映射当创建MyObject时则会抛出异常,而IMyInterface则不会。在一些情况下往往希望某个属性只有getter而没有setter,或者setter只有在第一次注入时可以使用,之后属性的值就不应该被修改。比如MyObject的两个属性应该只有getter。这个时候建议使用Lazy<T>和Unity Resolve的Func<T>或者通过构造函数注入。
1 public static class AppDomainUnity 2 { 3 public static readonly IUnityContainer Instance = new UnityContainer(); 4 } 5 6 public sealed class MyObject 7 { 8 private Lazym_myInterface; 9 private Lazy m_myInterface2;10 11 public MyObject()12 {13 m_myInterface = new Lazy (AppDomainUnity.Instance.Resolve >());14 m_myInterface2 = new Lazy (AppDomainUnity.Instance.Resolve >());15 }16 17 public IMyInterface MyInterface18 {19 get { return m_myInterface.Value; }20 }21 22 public IMyInterface2 MyInterface223 {24 get { return m_myInterface2.Value; }25 }26 }27 28 IUnityContainer unityContainer = AppDomainUnity.Instance;29 30 unityContainer.RegisterType ();31 unityContainer.RegisterType ();32 33 MyObject myObject = unityContainer.Resolve ();