无法使用Castle Windsor在MVC 5 Web API项目中执行依赖项注入

无法使用Castle Windsor在MVC 5 Web API项目中执行依赖项注入

问题描述:

下面是我想使用温莎城堡实例化的控制器的代码。

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

我已经在Global.asax中编写了以下代码。 cs

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.

请务必阅读Mark Seemann撰写的有关WEB API的所有文章。
您可以在此处开始,然后遍历Web API 此处

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.