Ninject - 使用属性注入,而不是构造器注入 [英] Ninject - using property injection instead of constructor injection

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

问题描述

长话短说,我正在尝试使用ELMAH与MVC 2和Ninject,我需要用参数构造函数。我创建了一个初始后约在这里:使用一个无参数的控制器构造与Ninject <? / A>

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

    ...
}



这样:

to this:

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 你需要incject 这个(即你的有关部门控制器到Ninject籽粒因此,它是这样的:

Basically when you initialise DepartmentsController you need to incject this (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.

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

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