如何在实体框架DbContext中使用依赖注入?

omk*_*kla 7 c# asp.net entity-framework

我目前正致力于为网站添加新功能.

我有一个使用EF6创建的DbContext类.

该网站使用主布局,其中子布局根据请求的页面呈现.我想使用依赖注入来访问Sublayouts中的DbContext.通常,我会使用Controller来处理调用,但是,在这种情况下,我想跳过它.

另外,我希望保持实现的灵活性,以便添加新的DbContexts,我将能够轻松使用它们.

我在考虑创建一个"IDbContext"接口.

我将使用新界面(让我们说"IRatings")实现这个界面.

我是以正确的方式去做的吗?

有什么想法吗?

Sze*_*zer 7

我更喜欢SimpleInjector,但它对于任何其他IoC容器都没有那么大的差别.

更多信息在这里

ASP.Net4的示例:

// You'll need to include the following namespaces
using System.Web.Mvc;
using SimpleInjector;
using SimpleInjector.Integration.Web;
using SimpleInjector.Integration.Web.Mvc;

    // This is the Application_Start event from the Global.asax file.
    protected void Application_Start()
    {
        // Create the container as usual.
        var container = new Container();
        container.Options.DefaultScopedLifestyle = new WebRequestLifestyle();

        // Register your types, for instance:
        container.Register<IDbContext, DbContext>(Lifestyle.Scoped);

        // This is an extension method from the integration package.
        container.RegisterMvcControllers(Assembly.GetExecutingAssembly());

        // This is an extension method from the integration package as well.
        container.RegisterMvcIntegratedFilterProvider();

        container.Verify();

        DependencyResolver.SetResolver(new SimpleInjectorDependencyResolver(container));
    }
Run Code Online (Sandbox Code Playgroud)

这样的注册将创建DbContext每个WebRequest并为您关闭它.因此,您只需要IDbContext在控制器中注入并照常使用它,而无需using:

public class HomeController : Controller
{
    private readonly IDbContext _context;

    public HomeController(IDbContext context)
    {
        _context = context;
    }

    public ActionResult Index()
    {
        var data = _context.GetData();
        return View(data);
    }
}
Run Code Online (Sandbox Code Playgroud)