c# - Ninject: Controller 的实体上下文

标签 c# asp.net-mvc-3 dependency-injection entity-framework-4.1 ninject

我知道已经提出了一千零一个与此主题相关的问题,但我已经回答了至少一打,但仍无法将这些问题联系起来。我正在尝试为实体上下文设置依赖注入(inject)。

我总是像在 MS 教程中看到的那样创建我的实体上下文,如下所示:

public class UserController : Controller
{
    private DbEntities db = new DbEntities();

}

最近的阅读告诉我,这不再是(如果曾经是)最佳实践,应该使用依赖注入(inject)方法。 Ninject 经常被提及,但我看到你如何从我所拥有的转向 Ninject documentation 中给出的示例。 .

完成后应该是这样的吧?

public class UserController : Controller
{
    private DbEntities db;

    public UserController(DbEntities context)
    {
        db = context;
    }
}

文档以“在上一步中我们已经准备好 Controller 注入(inject)所需的一切”开头。这真是令人困惑,因为上一步是安装。我使用 Nuget 方法安装,但我不知道它说“现在加载你的模块或在 RegisterServices 方法中定义绑定(bind)”是什么意思。我该怎么做,实体是模块还是绑定(bind)?感觉文档太少了。

很抱歉,如果我跳过了文档中的一些关键内容,我已经在论坛之间来回奔波了几个小时,试图弄清楚这一步骤。

最佳答案

I used the Nuget method to install, but I don't know what it means when it says "Now load your modules or define bindings in RegisterServices method." How do I do that, and is entity a module or a binding?

Nuget 安装实际上已经为您做了很多事情。最重要的是它将 Ninject 设置为 Controller 工厂,这意味着 Ninject 将创建您的 Controller 并能够传递您向其注册的所有依赖项。

如果您检查 App_Start 文件夹,您将找到一个文件 NinjectMVC3.cs。已经有一个空方法 RegisterServices(),您可以使用它来注册您的依赖项。

对于您的示例,您必须能够解析 DbEntities。最简单最基本的方法是:

kernel.Bind<DbEntities>().ToSelf();

也就是说,您确实应该将接口(interface)传递给 Controller ​​,以便 Controller 不依赖于 Entity Framework ,使用抽象和注册具体类以在 IoC 容器中使用是依赖注入(inject)的主要原因之一。

这应该给您一个开始 - 您链接到的文档似乎有点过时了。我建议查看 Ninject MVC3 sample在 github 上。

关于c# - Ninject: Controller 的实体上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9245511/

相关文章:

c# - 使用模型创建文件下载链接 MVC3 Razor View

c# - 使用 ASP.Net MVC3 显示 byte[] 中包含的图像

java - 在 Presenter 类中实例化 DI 组件是一种好习惯吗?

c# - 使用 WebBrowser 控件的双面打印仅打印 1 面

c# - 完成队列卡住

c# - 保存大量外汇金融报价数据的最佳方式

asp.net-mvc - 如何为 ASP.NET MVC 上的 GET 和 POST 操作绑定(bind)字典类型参数

javascript - 通过依赖注入(inject)传递参数

java - 如何找到 Spring beans.xml

c# - Lambda 表达式创建不相关的编译错误