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

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

该网站使用主版式,在该版式中,子版式将根据请求的页面进行渲染。我想使用依赖注入(inject)来访问Sublayouts中的DbContext。通常,我将使用 Controller 来处理调用,但是,在这种情况下,我想跳过它。

另外,我想保持实现的灵活性,以便添加新的DbContext,这样我就可以轻松使用它们。

我当时正在考虑创建一个接口(interface)“IDbContext”。

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

我会以正确的方式进行操作吗?

有什么想法吗?

最佳答案

我更喜欢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并为您关闭它。因此,您只需要在 Controller 中注入(inject)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);
    }
}

关于c# - 如何在 Entity Framework DbContext中使用依赖注入(inject)?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35696411/

10-12 00:01
查看更多