Unity Property Dependency Injection
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<IMyInterface, MyInterfaceImpl>(); 14 unityContainer.RegisterType<IMyInterface2, MyInterface2Impl>(); 15 16 MyObject myObject = unityContainer.Resolve<MyObject>();
MyObject的MyInterface属性被注入了MyInterfaceImpl,但是MyInterface2属性由于没有DependencyAttribute则不被注入。Unity还提供了OptionalDependencyAttribute,当某个属性依赖的类型没有被注册或者注入失败时,属性的值为null。
1 public sealed class MyObject 2 { 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 Lazy<IMyInterface> m_myInterface; 9 private Lazy<IMyInterface2> m_myInterface2; 10 11 public MyObject() 12 { 13 m_myInterface = new Lazy<IMyInterface>(AppDomainUnity.Instance.Resolve<Func<IMyInterface>>()); 14 m_myInterface2 = new Lazy<IMyInterface2>(AppDomainUnity.Instance.Resolve<Func<IMyInterface2>>()); 15 } 16 17 public IMyInterface MyInterface 18 { 19 get { return m_myInterface.Value; } 20 } 21 22 public IMyInterface2 MyInterface2 23 { 24 get { return m_myInterface2.Value; } 25 } 26 } 27 28 IUnityContainer unityContainer = AppDomainUnity.Instance; 29 30 unityContainer.RegisterType<IMyInterface, MyInterfaceImpl>(); 31 unityContainer.RegisterType<IMyInterface2, MyInterface2Impl>(); 32 33 MyObject myObject = unityContainer.Resolve<MyObject>();
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?