Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot Inject Dependencies into Asp.net MVC 4 Web API Controller using Windsor Container

I am unable to configure Windsor Container with asp.net web api, though it working fine with regular controller(IController).

I have regular controller and api controller in same project.

Here is the code for regular controller which working fine:

/// <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;
        }

}

and in global.asax.cs

 container.Register(Component.For<IWindsorContainer>().Instance(container));
  container.Register(Component.For<IControllerActivator>().ImplementedBy<WindsorControllerActivator>());

and below is the problematic code:

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;
        }
    }

and installer:

 container.Register(Component.For<IHttpControllerActivator>().ImplementedBy<WindsorApiControllerActivator>());

however, i am never able to execute WindsorApiControllerActivator.

when, i put debugger in WindsorControllerActivator it work as expected, but for WindsorApiControllerActivator it never get executed.

your help will be appreciated

like image 461
aamir sajjad Avatar asked Nov 12 '22 21:11

aamir sajjad


1 Answers

I added the following code in global.asax.cs, and it works:)

 _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);
like image 99
aamir sajjad Avatar answered Nov 15 '22 12:11

aamir sajjad