无法使用Castle Windsor在MVC 5 Web API项目中执行依赖项注入 [英] Unable to perform dependency injection in MVC 5 Web API project using Castle Windsor

查看:138
本文介绍了无法使用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.

这篇关于无法使用Castle Windsor在MVC 5 Web API项目中执行依赖项注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆