Asp.net mvc 在基本控制器类中具有实体框架的Ninject

Asp.net mvc 在基本控制器类中具有实体框架的Ninject,asp.net-mvc,dependency-injection,ninject,Asp.net Mvc,Dependency Injection,Ninject,我正在尝试在ASP.NETMVC项目中使用Ninject。以下是我在项目中使用实体框架的计划- //Web.config <connectionStrings> <add name="MyTestDbEntities" connectionString="...." /> </connectionStrings> //Base controller public abstract class BaseController : Controller {

我正在尝试在ASP.NETMVC项目中使用Ninject。以下是我在项目中使用实体框架的计划-

//Web.config 
<connectionStrings>
   <add name="MyTestDbEntities" connectionString="...." />
</connectionStrings>

//Base controller
public abstract class BaseController : Controller
{
    protected readonly MyTestDbEntities Db;
    public BaseController() { }
    public BaseController(MyTestDbEntities context)
    {
        this.Db = context;
    }
}

public class HomeController : BaseController
{
    public ActionResult Index()
    {
        Db.Students.Add(new Student() { StudentName="test"});
        Db.SaveChanges();
        return View();
    }
}
//Web.config
//基本控制器
公共抽象类BaseController:控制器
{
受保护的只读MyTestDbEntities数据库;
公共BaseController(){}
公共BaseController(MyTestDbEntities上下文)
{
this.Db=上下文;
}
}
公共类HomeController:BaseController
{
公共行动结果索引()
{
Add(newstudent(){StudentName=“test”});
Db.SaveChanges();
返回视图();
}
}
我想使用Ninject如下-

kernel.Bind<MyTestDbEntities>().To<BaseController>().InRequestScope();
kernel.Bind().To().InRequestScope();
但是它说-

The type 'NinjectTest.BaseController' cannot be used as type parameter 
'TImplementation' in the generic type or method 
'IBindingToSyntax<MyTestDbEntities>.To<TImplementation>()'. 
There is no implicit reference conversion from 'NinjectTest.BaseController' 
to 'NinjectTest.Models.MyTestDbEntities'.   
类型“NinjectTest.BaseController”不能用作类型参数
泛型类型或方法中的“TImplementation”
'IBindingToSyntax.To()'。
“NinjectTest.BaseController”中没有隐式引用转换
至“NinjectTest.Models.MyTestDbEntities”。

您能建议我如何配置Ninject以在项目中工作吗?

通常发生的情况是将接口绑定到实现它的具体类型,即:

kernel.Bind<IMyService>().To<MyServiceImpl>();
然后它将被注入到控制器构造函数中,但是所有从BaseController派生的控制器都需要有一个请求DbContext作为参数的构造函数

public HomeController(MyTestDbEntities db) : base(db) { }
但是,请注意,您正在具体实现(DbContext)上创建一个依赖项,这有点违背了依赖项注入的目的

public HomeController(MyTestDbEntities db) : base(db) { }