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

相關文章
相關標籤/搜索