我無法使用asp.net web api配置Windsor容器,但它可以與常規控制器(IController)一起正常工作。無法使用Windsor容器將依賴項注入到Asp.net MVC 4 Web API控制器
我在同一個項目中有正規的控制器和api控制器。
這裏是常規控制器,其細工作的代碼:
/// <summary>
/// Controller Factory class for instantiating controllers using the Windsor IoC container.
/// </summary>
public class WindsorControllerActivator : IControllerActivator
{
private readonly IWindsorContainer container;
public WindsorControllerActivator(IWindsorContainer container)
{
this.container = container;
}
public IController Create(RequestContext requestContext, Type controllerType)
{
var controller = (IController)container.GetService(controllerType);
return controller;
}
}
和的global.asax.cs
container.Register(Component.For<IWindsorContainer>().Instance(container));
container.Register(Component.For<IControllerActivator>().ImplementedBy<WindsorControllerActivator>());
和下面是有問題的代碼:
public class WindsorApiControllerActivator : IHttpControllerActivator
{
private readonly IWindsorContainer container;
public WindsorApiControllerActivator(IWindsorContainer container)
{
this.container = container;
}
public IHttpController Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)
{
var controller = (IHttpController)container.GetService(controllerType);
return controller;
}
}
和安裝者:
container.Register(Component.For<IHttpControllerActivator>().ImplementedBy<WindsorApiControllerActivator>());
但是,我永遠無法執行WindsorApiControllerActivator。
當我把調試器放在WindsorControllerActivator中時,它按預期工作,但是對於WindsorApiControllerActivator它永遠不會執行。
您的幫助將不勝感激
你如何註冊你的容器作爲dependencyresolver? – nemesv
爲什麼要定製WindsorApiControllerActivator,而我沒有看到任何特殊處理? –
Cuong le:因爲我在api控制器中使用Nhibernate Session對象 [HttpPost] 公共的IList 搜索(SearchViewModel模型) { 的IList searchResultViewModels = SearchVenues(模型); return searchResultViewModels; //返回「Hello World」; } –
public ISession NSession {get;組; } public VendorController(ISession session) {NSession = session; } //獲取API/