0

我当前的堆栈是 ASP.NET MVC 4 和 Entity Framework 5.0。我通过 NuGet 安装了 ninject.mvc3,下面显示的代码运行良好:

public class SessionsController : Controller
{
    // use "kernel.Bind<MyContext>().ToSelf().InRequestScope();" 
    // to inject MyContext
    private MyContext _context;

    public SessionsController(MyContext context)
    {
        _context = context;
    }

    [HttpGet]
    public ActionResult Login()
    {
        System.Diagnostics.Debug.WriteLine(_context.Users.Count());
        return View();
    }
}

}

现在,我想为我的控制器提取一个 BaseController:

public class BaseController : Controller
{
    protected MyContext _context;

    public BaseController(MyContext context)
    {
        _context = context;
    }

    // I don't know what should be write here and 
    // base controller must have a parameterless constructor
    public BaseController() 
    {

    }
}

然后我让 SessionsController 从 BaseController 继承。当我运行代码时,抛出了一个异常

“对象引用未设置为对象的实例。(使用 MyContext)”

我用错了 Ninject 吗?

--UPDATED-- ninject 的 NinjectWebCommon.cs 的代码

    /// <summary>
    /// Load your modules or register your services here!
    /// </summary>
    /// <param name="kernel">The kernel.</param>
    private static void RegisterServices(IKernel kernel)
    {
        kernel.Bind<TelesingContext>().ToSelf().InRequestScope();
    }        

--UPDATED--编辑后的 ​​SessionsController.cs 代码

public class SessionsController : BaseController
{
    [HttpGet]
    public ActionResult Login()
    {
        System.Diagnostics.Debug.WriteLine(_context.Users.Count());
        return View();
    }
}

}

4

2 回答 2

1

您的问题不在于 Ninject 或 MVC。您在派生类上缺少构造函数。

因为构造函数在任何方面都不是多态的(而是只能被链接),所以您仍然必须在派生类上定义一个构造函数,该构造函数接受 aMyContext并将其传递给基构造函数:

public class SessionsController : BaseController
{
    public SessionsController(MyContext context) : base(context) { }

    [HttpGet]
    public ActionResult Login()
    {
        System.Diagnostics.Debug.WriteLine(_context.Users.Count());
        return View();
    }
}

出现异常的原因是,如果您在类中未定义构造函数并且基类具有无参数构造函数,则 C# 编译器会自动在调用基类的类中插入一个无参数构造函数。因为该_context变量从未被设置,所以您的操作受到了NullReferenceException影响Login

于 2012-10-08T19:14:01.603 回答
0

做你正在做的事情真的没有太多好处。如果要在基类中使用构造函数,C# 要求为派生类创建构造函数。因此,您需要这样做:

public class Derived : Base
{
    public Derived(MyContext context) : base(context) { }
}

如您所见,从基本上下文派生几乎一样多的工作,那么重点是什么?除了强制执行标准流程。

BaseController 只需要一个无参数构造函数,因为您尚未定义应如何从派生类调用基构造函数。

Ninject 不能神奇地将参数插入基类,只有你的派生类才能做到。

于 2012-10-08T16:12:20.160 回答