无法使用Windsor Container将依赖项注入Asp.net MVC 4 Web API控制器

aam*_*jad 5 asp.net-mvc castle-windsor ioc-container asp.net-mvc-4 asp.net-web-api

我无法使用asp.net web api配置Windsor Container,尽管它与常规控制器(IController)配合良好.

我在同一个项目中有常规控制器和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;
        }

}
Run Code Online (Sandbox Code Playgroud)

在global.asax.cs中

 container.Register(Component.For<IWindsorContainer>().Instance(container));
  container.Register(Component.For<IControllerActivator>().ImplementedBy<WindsorControllerActivator>());
Run Code Online (Sandbox Code Playgroud)

以下是有问题的代码:

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;
        }
    }
Run Code Online (Sandbox Code Playgroud)

和安装人员:

 container.Register(Component.For<IHttpControllerActivator>().ImplementedBy<WindsorApiControllerActivator>());
Run Code Online (Sandbox Code Playgroud)

但是,我永远无法执行WindsorApiControllerActivator.

什么时候,我把调试器放在WindsorControllerActivator中它按预期工作,但对于WindsorApiControllerActivator它永远不会被执行.

你的帮助将不胜感激

aam*_*jad 1

我在 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);
Run Code Online (Sandbox Code Playgroud)