3月12日,Unity 又釋出了正式釋出之前的版本,這個版本提供了安裝程式.并且提供了一個依賴注入在實作方式:Setter injection 的配置API。之前釋出的版本,屬性注入需要用[Dependency], 這種設計Unity就侵入到你的元件了。現在可以通過ConfiguringInjection。
例如StoplightPresenter依賴于Stoplight 和StoplightSchedule ,可以在屬性打标簽[Dependency],也可以去掉這個标記,然後在UnityContainer内通過配置API配置:
public class StoplightPresenter
{
private Stoplight stoplight;
private StoplightSchedule schedule;
//[Dependency]
public Stoplight Stoplight
{
get { return stoplight; }
set { stoplight = value; }
}
// [Dependency]
public StoplightSchedule Schedule
get { return schedule; }
set { schedule = value; }
private IStoplightView view;
……
}
配置代碼如下:
IUnityContainer container = new UnityContainer()
.AddNewExtension<SimpleEventBrokerExtension>()
.RegisterType<ILogger, TraceLogger>()
.RegisterType<IStoplightTimer, RealTimeTimer>();
container.Configure<InjectedMembers>()
.ConfigureInjectionFor<StopLight.Logic.Stoplight>(
new InjectionProperty("Logger")
);
.ConfigureInjectionFor<StoplightPresenter>(
new InjectionProperty("Stoplight"),
new InjectionProperty("Schedule")
Unity Application Block雖然發展時間不長,主要是基于從企業類庫2.0開始出現的ObjectBuilder發展而來,下一個微軟Enterprise Library的版本V4——将預置支援依賴注入。依賴注入将通過容器以獨立或作為庫的一部分來提供。需要更深入的學習Unity Application Block,可看園子裡的TerryLee、doriandeng和overred的相關文章:
TerryLee的Unity Application Block
依賴注入容器Unity Application Block(1):快速入門
Enterprise Library 4.0中的依賴注入容器(Unity)預覽
doriandeng的Unity
使用 Unity(一):Unity 應用程式塊容器介紹
使用 Unity(二):配置 Unity 、讀取配置資訊和擷取對象
使用 Unity Application Block(三):了解和使用依賴注入的鍵
Unity Feb 26 Weekly Drop
overred的 ① NET Framework
依賴注入容器Unity Application Block(2):Unity的春天
順便學習一下英語的還可以看:
Unity Dependency Injection IoC Screencast
Unity IoC and ASP.NET MVC Framework - Dependency Injection of Controllers
Unity Nested Containers - IUnityParentContainer and CreateChildContainer
Unity IoC - February 26 Weekly Drop - LifetimeManagers TearDown Extensions and IDisposable
Using Unity and the ASP.NET MVC Preview 2
本文轉自 張善友 51CTO部落格,原文連結:http://blog.51cto.com/shanyou/73541,如需轉載請自行聯系原作者