Unity 依赖注入之二

1. 构造子注入

1.1 构造子注入初级代码

container.RegisterType<IMyWork, MyWork>(new InjectionConstructor(new Book("Mybook"))

 

1.2 在子构造子注入时增加unity依赖注入

复制代码
public class MyWork : IMyWork
    {
        public Book mybook;
        public MyWork(Book mybook)
        {
            this.mybook = mybook;
        }
        public string Work()
        {
            return "Work!";
        }
        public Book GetBook()
        {
            return this.mybook;
        }
    }
    public interface IMyWork
    {
        string Work();
        Book GetBook();
    }
复制代码

 

2. 注册泛型

2.1 注册泛型的方式一

//方式一
container.RegisterType(
   typeof(IMessageQueue<>),
   typeof(MessageQueue<>),
   new InjectionConstructor(storageAccountType,retryPolicyFactoryType, typeof(string))
);

 

2.2 注册泛型的方式二

//方式二
cntainer.RegisterType<IBlobContainer<SurveyAnswer>,EntitiesBlobContainer<SurveyAnswer>>(    
    new InjectionConstructor(storageAccountType, retryPolicyFactoryType, typeof(string))
);

 

3. 延迟加载

// Register the type 
container.RegisterType<MySampleObject>(new InjectionConstructor("default")); 
// Resolve using Lazy<T> 
var defaultLazy = container.Resolve<Lazy<MySampleObject>>(); 
// Use the resolved object 
var mySampleObject = defaultLazy.Value

 

4. 单例

通常情况下实现单例模式,在类中定义一个方法如Instance返回实例,但是这样有一种情况每一个类都要创建代码重复量多,同时将对象的生命周期与类本身职责耦合在一起。

下面是将生命周期职责移动到Unity上。

//方式一 通过ContainerControlledLifetimeManager创建单例
container.RegisterType<IMyWork, MyWork>(new ContainerControlledLifetimeManager());
//方式二 通过RegisterInstance创建单例
container.RegisterInstance<IMyWork>(new MyWork());

然后我们通过Resolve再次获取对象是就是一个上次创建的对象。

5. 延迟加载加单例

// Register the type with a lifetime manager 
container.RegisterType<MySampleObject>("other", new ContainerControlledLifetimeManager(),  new InjectionConstructor("other")); 
// Resolve the lazy type 
var defaultLazy1 = container.Resolve<Lazy<MySampleObject>>("other"); 
// Resolve the lazy type a second time 
var defaultLazy2 = container.Resolve<Lazy<MySampleObject>>("other"); 
// defaultLazy1 == defaultLazy2 is false 
// defaultLazy1.Value == defaultLazy2.Value is true

 

这是本人学习Unity的记录

Unity4.0的使用

Unity 依赖注入之一

posted @   程序之美~我爱上编程  阅读(1213)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示