Unable to perform dependency injection in MVC 5 Web API project using Castle Windsor

╄→尐↘猪︶ㄣ 提交于 2019-12-11 20:45:48

问题


Below is the code for controller I want to instantiate using Windsor Castle.

public class TestController : ApiController
{
    private ITestService _testService = null;

    public TestController(ITestService testService)
    {
        _testService = testService;
    }

    public IList<TestClass> Get()
    {
        IList<TestClass> testObjects = _testService.GetAll().ToList();
        return testObjects;
    }
}

I've written following code in Global.asax.cs

    protected void Application_Start()
    {
        ........................

        InitializeServiceLocator();
    }

    private static void InitializeServiceLocator()
    {
        _container = new WindsorContainer().Install(FromAssembly.This());

        var controllerFactory = new WindsorControllerFactory(_container.Kernel);
        ControllerBuilder.Current.SetControllerFactory(controllerFactory);
    }

Here is the code for installer =>

    public class ControllerInstaller : IWindsorInstaller
{
    public void Install(IWindsorContainer container, IConfigurationStore store)
    {
        if (container == null)
        {
            throw new ArgumentNullException("container");
        }

        if (store == null)
        {
            throw new ArgumentNullException("store");
        }
        //All MVC controllers
        container.Register(Classes.FromThisAssembly().BasedOn<IHttpController>().LifestylePerWebRequest());

        AddComponentsTo(container);
    }

    private void AddComponentsTo(IWindsorContainer container)
    {
        container.Register(
             ///DBContext
             Component.For<DbContext>().ImplementedBy<SCFEntities>().LifestyleTransient());

        container.Register(
                            Classes.FromAssemblyNamed("MyProject.ApplicationServices").Pick().WithService.DefaultInterfaces().LifestylePerWebRequest(),
            Classes.FromAssemblyNamed("MyProject.Data").Pick().WithService.DefaultInterfaces().LifestylePerWebRequest());
    }
}

The problem is the controller instance is not created using parameterized constructor. It is expecting a parameterless constructor. Could anybody point out where I am going wrong? Thanks.


回答1:


Be sure to read all the articles regarding WEB API that Mark Seemann wrote. You can start here and then traverse the archive for Web API here.

Read the first article and then traverse the archive. Everything is here.



来源:https://stackoverflow.com/questions/26607262/unable-to-perform-dependency-injection-in-mvc-5-web-api-project-using-castle-win

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!