ASP.NET Web API - 使用 Castle Windsor 依赖注入

示例代码

项目启动时,创建依赖注入容器

定义一静态容器 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

posted on 2015-06-13 22:16  iSun  阅读(4268)  评论(1编辑  收藏  举报