標籤:
範例程式碼
項目啟動時,建立依賴注入容器
定義一靜態容器 IWindsorContainer
1 private static IWindsorContainer _container;
在 Application_Start() 中,建立該容器
1 _container = new WindsorContainer();
調用 Container Install 方法,向容器內註冊組件
1 _container.Install(FromAssembly.This());
該語句會調用整個程式集中所有實現了 IWindsorInstaller 介面類中的Install方法以向容器的註冊組件。如下列代碼:
1 public void Install(IWindsorContainer container, IConfigurationStore store)2 {3 container.Register(4 Component.For<IDPlatypusRepository>().ImplementedBy<DPlatypusRepository>().LifestylePerWebRequest());5 }
特別列出向 Container 中註冊 Controler 的代碼:
1 public void Install(IWindsorContainer container, IConfigurationStore store)2 {3 container.Register(Classes.FromThisAssembly()4 .BasedOn<ApiController>().LifestylePerWebRequest());5 }
定義實現 IDependencyResolver 介面的 WindsorDependencyResolver 類,作為全域 HttpConfiguration 的 Resolver
var dependencyResolver = new WindsorDependencyResolver(_container);configuration.DependencyResolver = dependencyResolver;
建立一新 IHttpControllerActivator,更改 Controller 建立方式為從容器 Container 中擷取
實現 IHttpControllerActivator 介面 Create 方法
1 public IHttpController Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)2 {3 var controller = (IHttpController)_container.Resolve(controllerType);4 5 request.RegisterForDispose(6 new Release(() => _container.Release(controller)));7 8 return controller;9 }
並且註冊當 web request 被 Dispose 的時候,Dispose 該 Controller。
替換 Default IHttpControllerActivator 行為
GlobalConfiguration.Configuration.Services.Replace(typeof(IHttpControllerActivator),new WindsorCompositionRoot(container));
參考資料:
Simplest Possible ASP.NET Web API Project that Implements IoC/DI using Castle Windsor
http://www.codeproject.com/Articles/710662/Simplest-Possible-ASP-NET-Web-API-Project-that-Imp
WebAPI Dependency Injection
https://github.com/ucdavis/UCDArch/wiki/WebAPI-Dependency-Injection
Difference between inheriting ApiController vs. IHttpController
http://stackoverflow.com/questions/21464909/difference-between-inheriting-apicontroller-vs-ihttpcontroller
ASP.NET WEB API 2: HTTP MESSAGE LIFECYLE
http://www.asp.net/posters/web-api/asp.net-web-api-poster.pdf
使用 Castle Windsor 實現 Web API 依賴注入
http://beginor.github.io/2014/12/21/webapi-dependency-injection-with-castle-windsor.html
ASP.NET Web API - 使用 Castle Windsor 依賴注入