如何在entity frameworkDbContext中使用dependency injection?

我目前正致力于为网站添加新function。

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

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

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

我在考虑创建一个“IDbContext”接口。

我将使用新界面(让我们说“IRatings”)实现这个界面。

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

有什么想法吗?

我更喜欢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(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)); } 

这样的注册将为每个WebRequest创建DbContext并为您关闭它。 所以你只需要在你的控制器中注入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); } }