Ninject with Entity Framework在基本控制器类中

时间:2017-05-30 14:01:48

标签: asp.net-mvc dependency-injection ninject

我正在尝试在ASP.NET MVC项目中使用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();
    }
}

我想使用Ninject如下 -

kernel.Bind<MyTestDbEntities>().To<BaseController>().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'.   

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

1 个答案:

答案 0 :(得分:0)

通常会将接口绑定到实现它的具体类型,即:

kernel.Bind<IMyService>().To<MyServiceImpl>();

您无需创建绑定即可将服务注入每个使用者(即BaseController)。您可以通过在构造函数(构造函数注入)中请求它来使用绑定,或者使用[Inject](属性注入或setter注入)装饰属性

在您的示例中,您需要为DbContext创建一个绑定:

kernel.Bind<MyTestDbEntities>().ToSelf().InRequestScope();

然后它将被注入到Controller构造函数中,但是从BaseController派生的所有控制器都需要具有要求DbContext作为参数的构造函数

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