Unity 依赖注入之二

1. 构造子注入html

1.1 构造子注入初级代码web

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

 

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

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 注册泛型的方式一this

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

 

2.2 注册泛型的方式二url

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

 

3. 延迟加载spa

// 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. 单例code

一般状况下实现单例模式,在类中定义一个方法如Instance返回实例,可是这样有一种状况每个类都要建立代码重复量多,同时将对象的生命周期与类自己职责耦合在一块儿。orm

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

//方式一 经过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 依赖注入之一

相关文章
相关标签/搜索