使用属性注入代替构造函数注入 [英] Using property injection instead of constructor injection

查看:263
本文介绍了使用属性注入代替构造函数注入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

长话短说,我正在尝试将ELMAH与MVC 2和Ninject一起使用,并且我需要使用无参数构造函数.我在此处创建了有关它的初始文章:在Ninject中使用无参数控制器构造函数吗?

Long story short, I'm trying to use ELMAH with MVC 2 and Ninject, and I need to use parameterless constructors. I created an initial post about it here: Using a parameterless controller constructor with Ninject?

建议我使用属性注入而不是构造函数注入.所以我从这里搬走了:

I was advised to use property injection instead of constructor injection. So I moved from this:

public class DepartmentsController : Controller
{
    private IDepartmentsRepository departmentsRepository;

    public DepartmentsController(IDepartmentsRepository departmentsRepository)
    {
        this.departmentsRepository = departmentsRepository;
    }

    ...
}

对此:

public class DepartmentsController : Controller
{
    private IDepartmentsRepository _departmentsRepository;

    [Inject]
    public IDepartmentsRepository DepartmentsRepository
    {
        get { return _departmentsRepository; }
        set { _departmentsRepository = value; }
    }

    ...
}

但是在其他控制器功能中,无论我尝试访问DepartmentsRepository还是_departmentsRepository,在尝试访问它时,都会得到一个对象引用未设置为对象实例的错误.

But in my other controller functions, whether I try to access DepartmentsRepository or _departmentsRepository, I get an object reference not set to an instance of an object error when I try to access it.

在这里我还需要做些其他事情吗?

Is there something else I need to do here?

推荐答案

我遇到了类似的问题.看看我的问题:将Ninject与Membership.Provider一起使用.

I had a similar problem. Have a look at my questions: Using Ninject with Membership.Provider.

基本上,当您初始化DepartmentsController时,您需要注入this(即,您的部门控制器进入Ninject内核.所以类似:

Basically when you initialise DepartmentsController you need to injectthis (i.e. your departments controller into your Ninject kernal. So its something like:

public class DepartmentsController : Controller
{
  private IDepartmentsRepository _departmentsRepository;

  [Inject]
  public IDepartmentsRepository DepartmentsRepository
  {
    get { return _departmentsRepository; }
    set { _departmentsRepository = value; }
  }

  public DepartmentsController()
  {
    NinjectHelper.Kernel.Inject(this);
  }
}

在这种情况下,NinjectHelper会获取当前的Ninject内核.

Where NinjectHelper in this case gets the current Ninject Kernel.

这篇关于使用属性注入代替构造函数注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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