5

我无法使用 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;
        }

}

在 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,它永远不会被执行。

您的帮助将不胜感激

4

2 回答 2

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);
于 2012-09-24T05:37:54.433 回答
0

您应该非常小心地为 Windosr 使用 IDependencyResolver,而无需考虑 decomissiong/release 问题。

看看这个实现 http://nikosbaxevanis.com/2012/06/04/using-the-web-api-dependency-resolver-with-castle-windsor-part-2/ 我还没试过,但这似乎是当前 webapi 版本的必经之路

于 2012-09-24T09:59:16.643 回答