Castle Windsor ApiController Factory implementation for ASP.NET Web API

前端 未结 6 1942
傲寒
傲寒 2020-12-16 03:07

I know it\'s possible to use DependencyResolver and register Castle Windsor with MVC but due to the issues described in https://stackoverflow.com/a/4889222/139392 we have st

6条回答
  •  我在风中等你
    2020-12-16 03:47

    I have managed to resolve from my windsor container by using GlobalConfiguration.Configuration.ServiceResolver.SetResolver as shown here.

    Example Windsor Code

    private void BootStrapWindsorContainer()
    {
         _container = new WindsorContainer()
              .Install(FromAssembly.This());
    
         var controllerFactory = new WindsorControllerFactory(_container.Kernel);
    
         ControllerBuilder.Current.SetControllerFactory(controllerFactory);
         ServiceLocator.SetLocatorProvider(() => new WindsorServiceLocator(_container));
         GlobalConfiguration.Configuration.ServiceResolver.SetResolver(
             t =>
                 {
                     try
                    {
                        return _container.Resolve(t);
                    }
                    catch
                    {
                        return null;
                    }
                },
                t =>
                {
                    try
                    {
                        return _container.ResolveAll(t).OfType();
                    }
                    catch
                    {
                 return new List();
             }
        });
    }
    
    

    Returning null when you cannot resolve types works and it seems like MVC will new up the dependencies.

    Edit: Make sure you have an installer for IHttpController

    提交回复
    热议问题