Unity 依赖注入之二

2023-07-31,,

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 依赖注入之一

Unity 依赖注入之二的相关教程结束。

《Unity 依赖注入之二.doc》

下载本文的Word格式文档,以方便收藏与打印。