在MVC控制器中放置DbContext,哪种方式“更好”? [英] Dispose DbContext in MVC Controller, which way "better"?

查看:97
本文介绍了在MVC控制器中放置DbContext,哪种方式“更好”?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在MVC 5中,脚手架代码将类似于:

In MVC 5, the scaffolding codes will have something like:

    public class MyController : Controller
{
    private MyContext db = new MyContext();

    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
            db.Dispose();
        }
        base.Dispose(disposing);
    }

否则,我需要拥有

using (var db = new MyContext())
{...}

每个动作。

代码看起来不错,所以我不需要在每个动作中使用using。但是,这是否受程序员的青睐,还是这种样式相对于在需要使用dbcontext的每个操作中使用而言具有某些优势?

The codes look good, so I don't need to use using in each action. However, is this subject to preference of programmers, or such style has some advantage over using in each action that needs to use the dbcontext?

推荐答案

两种解决方案都很好-两种解决方案都将处理db上下文。但是我认为第二种选择会更好-在需要的地方创建数据库上下文。

Both solution are good - both solution will dispose db context. But in my opinion the second option will be better - you create db context just where you have to.

但是,如果另一个类(某些服务类)也使用db上下文怎么办?最好的做法是为整个Web请求提供一个数据库上下文。在这种情况下,您应该将先前创建的数据库上下文传递给所有使用数据库上下文的类,以防止在所有情况下都创建新的数据库上下文。因此,我将考虑使用IoC容器。 IoC容器将解决您的依赖关系,还将管理对象的生存期。波纹管

But what if another class (some service class) also uses db context. It is good practice to have one db context for the whole web request. In that case you should pass previous created db context to all classes that use db context to prevent creating new db context in all clases. So I will consider usage of IoC containers. IoC container will resolve your dependencies and also will mange object lifetime. Bellow

我列出了一些IoC容器:

I listed a few IoC containers:

这篇关于在MVC控制器中放置DbContext,哪种方式“更好”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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