我无法使用asp.net Web API配置Windsor Container,尽管它可以与常规controller(IController)正常工作。
我在同一项目中有常规 Controller 和api Controller 。
这是正常工作的 Controller 代码:
/// <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,它永远不会执行。
您的帮助将不胜感激
最佳答案
我在global.asax.cs中添加了以下代码,并且可以正常工作:)
_windsorContainer = new WindsorContainer();
_windsorContainer.Install(new EventSorbetInstaller());
DependencyResolver.SetResolver(new WindsorDependencyResolver(_windsorContainer));
ServiceLocator.SetLocatorProvider(() => new WindsorServiceLocator(_windsorContainer));
RegisterFilterProviders(FilterProviders.Providers, _windsorContainer);
var activator = _windsorContainer.Resolve<IHttpControllerActivator>();
GlobalConfiguration.Configuration.Services.Replace(typeof(IHttpControllerActivator), activator);
关于asp.net-mvc - 无法使用Windsor容器将依赖项注入(inject)Asp.net MVC 4 Web API Controller ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12558942/