Enterprise Library 4.0中的依賴注入容器(Unity)預覽

來源:互聯網
上載者:User
概述

之前我曾發過一篇Enterprise Library 4.0開發計劃中提到微軟在Enterprise Library 4.0將加入依賴注入容器,暫訂名為DIAB,現在微軟終於給它起了個正式的名字Unity,難道是“團結”的意思?:),在Unity最終將以兩種形式發布:獨立的容器組件和作為Enterprise Library 4.0的一部分,用微軟的話說“它是一個輕量級的、可擴充的依賴注入容器”,在ASP.NET MVC Framework推出後引起了業界極大的討論“MS MVC架構漩渦中的MonoRail未來”,不知道Unity推出之後會不會再出現一場“Unity漩渦中的Castle Windsor未來”或者“Unity漩渦中的Spring.Net未來”的討論。這裡先帶您提前預覽一下Unity。

Unity預覽

在Unity中將提供Register方法來註冊對象映射,使用Get方法獲得對象的執行個體,基本API如下:

public class UnityContainer : IDisposable{    // getting objects    public T Get<T>(string key) { }    public IEnumerable<T> GetAll<T>() { }    // type mapping    public UnityContainer Register<TFrom, TTo>(string key) where TTo : TFrom { }    // singleton support    public UnityContainer SetSingleton<T>(string key) { }    // support for registering existing objects    public UnityContainer RegisterInstance<T>(T existing, string key, bool overload) { }    // running existing objects through the container    public T BuildUp<T>(T existing, string key) { }}
典型使用

在Unity中,我們可以像如下代碼這樣加入組件:

UnityContainer container = new UnityContainer()              .Register<ILogger, TraceLogger>()              .Register<ISomething, Something>();

擷取對象執行個體:

ISomething some = container.Get<ISomething>();

用過Castle的朋友一定還記得,這似乎和Castle中的IOC容器非常像,在Castle的IOC容器中加入組件:

IWindsorContainer container = new WindsorContainer( new XmlInterpreter("http://www.cnblogs.com/BasicUsage.xml") );container.AddComponent( "txtLog", typeof(ILog), typeof(TextFileLog) );container.AddComponent( "format", typeof(ILogFormatter), typeof(TextFormatter) );

擷取對象執行個體:

ILog log = (ILog)container["txtLog"];

二者是不是有幾分相似呢?不知道Unity會給我們帶來哪些驚喜?

結束語

在ASP.NET MVC Framework推出後引起了業界極大的討論“MS MVC架構漩渦中的MonoRail未來”,不知道Unity推出之後會不會再出現一場“Unity漩渦中的Castle Windsor未來”或者“Unity漩渦中的Spring.Net未來”的討論。不管怎麼說,微軟推出Unity,我們又多了一種可供選擇的依賴注入容器。

參考:DIAB is now Unity

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.