现有 Castle Windsor MVC 配置
假设您有类似于Castle Windsor MVC 教程的 MVC 和 Castle Windsor 设置,使用Mark Seemann 的帖子 添加 IoC 以使 Web API 控制器利用依赖注入非常简单(请注意,他解释了为什么不使用 IDependencyResolver)。
从 Castle Windsor 教程中,您应该在Global.asax.cs
.
private static IWindsorContainer container;
protected void Application_Start()
{
//... MVC / Web API routing etc.
BootStrapper bs = new BootStrapper();
container = bs.ConfigureCastleWindsorMVC();
}
BootStrapper.ConfigureCastleWindsorMVC()
剪断
IWindsorContainer container = new WindsorContainer()
.Install(
new LoggerInstaller()
//...,
, new ControllersInstaller()
);
var controllerFactory = new WindsorControllerFactory(container.Kernel);
ControllerBuilder.Current.SetControllerFactory(controllerFactory);
return container;
所需的更改
从 Mark Seemann 的帖子中,您需要通过IHttpControllerActivator
. 这是您需要的他的适配器实现。
public class WindsorCompositionRoot : IHttpControllerActivator
{
private readonly IWindsorContainer container;
public WindsorCompositionRoot(IWindsorContainer container)
{
this.container = container;
}
public IHttpController Create(HttpRequestMessage request,
HttpControllerDescriptor controllerDescriptor, Type controllerType)
{
var controller =
(IHttpController)this.container.Resolve(controllerType);
request.RegisterForDispose(
new Release(() => this.container.Release(controller)));
return controller;
}
private class Release : IDisposable
{
private readonly Action release;
public Release(Action release) { this.release = release; }
public void Dispose()
{
this.release();
}
}
}
使用 IHttpControllerActivator 适配器和 MVC Castle Windsor 容器实现,您只需要在Global.asax.cs
(或者如果您使用的话,在 BootStrapper 中)配置它。它必须在 MVC 初始化之后,因为 MVC 初始化具有所有安装程序。
private static IWindsorContainer container;
protected void Application_Start()
{
// MVC / Web API routing etc.
BootStrapper bs = new BootStrapper();
container = bs.ConfigureCastleWindsorMVC();
// Web API Castle Windsor ++ ADD THIS ++
GlobalConfiguration.Configuration.Services.Replace(
typeof(IHttpControllerActivator),
new WindsorCompositionRoot(container));
}
最后结果:
Web API 控制器可以像使用 MVC 控制器一样使用注入的依赖项。
public class TestController : ApiController
{
private readonly ITestService TestService;
public TestController(ITestService testService)
{
this.TestService = testService;
}
// GET api/<controller>
public IEnumerable<string> Get()
{
return TestService.GetSomething();
//return new string[] { "value1", "value2" };
}
}