如何在实体框架DbContext中使用依赖注入? [英] How to use Dependency Injection with Entity Framework DbContext?

查看:221
本文介绍了如何在实体框架DbContext中使用依赖注入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在为网站添加新功能。

I am currently working on including a new functionality for a Website.

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

I have a DbContext class which I created using EF6.

该网站使用主版式,在该版式中子布局将根据请求的页面进行缩小。我想使用依赖注入来访问Sublayouts中的DbContext。通常,我将使用控制器来处理调用,但是在这种情况下,我想跳过该调用。

The website uses a Master Layout in which sublayouts are rendered depeding upon the page requested. I want to use Dependency Injection to access the DbContext in the Sublayouts. Generally, I would use a Controller to handle the calls, however, I want to skip that in this case.

此外,我想保持实现的灵活性,以便新的添加了DbContext,我将能够轻松使用它们。

Also, I want to keep the implementation flexible so that new DbContexts are added I will be able to use them easily.

我当时正在考虑创建一个接口 IDbContext。

I was thinking of creating an interface "IDbContext".

我将使用实现该接口的新接口(假设为 IRatings)。

I will have the new interface(let's say "IRatings") implementing this interface.

我要去吗

有什么想法吗?

推荐答案

I我更喜欢SimpleInjector,但与其他任何IoC容器都没有太大区别。

I am prefer SimpleInjector but it wont differ that much for any other IoC container.

更多信息此处

ASP.Net4示例:

Example for 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 中的c>并为您关闭它。因此,您只需要在控制器中注入 IDbContext 即可照常使用它,而无需使用

Such registration will create DbContext per every WebRequest and close it for you. So you simply need inject IDbContext in your controller and use it as usual without 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);
    }
}

这篇关于如何在实体框架DbContext中使用依赖注入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆