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

时间:2016-02-29 09:50:58

标签: c# asp.net entity-framework

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

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

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

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

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

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

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

有什么想法吗?

1 个答案:

答案 0 :(得分:7)

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

更多信息here

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));
    }

此类注册将为每个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);
    }
}