每个请求的静态方法中的EntityFramework DbContext

时间:2019-02-23 20:19:07

标签: asp.net-mvc entity-framework-6 asp.net-core-mvc asp.net-core-webapi dbcontext

每个网络请求,实体框架DbContext如何以静态方法工作?有性能问题吗?我下面有两节课。哪个更好用?还是不好?我们是否需要实例获取所有梨请求?有什么问题吗?

public class MyClassA 
{
    public static Product GetProduct(int Id) 
    {
        using(MyContext myContext = new MyContext())
        return myContext.Products.Where(x = > x.Id == Id).SingleOrDefault();
    }
}

public class MyClassB 
{
    MyContext myContext = new MyContext()

    public static Product GetProduct(int Id) 
    {
        return myContext.Products.Where(x = > x.Id == Id).SingleOrDefault();
    }
}

调用控制器

public class DefaultController : ControllerBase
{
    public Product GetProductStaticMethodinMyClassA(int Id)
    {
        return MyClassA.GetProduct(Id);
    }

    public Product GetProductStaticMethodinMyClassB(int Id)
    {
        return MyClassB.GetProduct(Id);
    }


    public Product GetProductinRequlurUse(int Id)
    {
        MyContext myContext = new MyContext();

        return myContext.Products.Where(x => x.Id == Id).SingleOrDefault();

    }
}

1 个答案:

答案 0 :(得分:1)

您需要为每个HTTP请求创建一个DbContext,即不要在多个请求之间共享相同的DbContext。

C#垃圾收集器一旦超出范围,就会自动处理DbContext,因此您不必将其放在using块中,但是,尽管如此,大多数人还是使用{ {1}}块和MS seems to encourage it

  

上下文的生存期始于创建实例并   在实例被处置或垃圾回收时结束。采用   如果希望上下文控制的所有资源都是   放置在块的末端。使用时,编译器   自动创建一个try / finally块并将调用处置在   终于挡住了。

using

关于public void UseProducts() { using (var context = new ProductContext()) { // Perform data access using the context } } 在控制器中的使用,您的问题是关于设计和基于意见的...如果您遵循DDD原则,则DbContext会进入基础结构层,而您的控制器属于表示层。 。,因此您一开始就不会直接在控制器中使用DbContext

如果要在控制器内部使用DbContext,则最好将其注入,而不是在控制器中对其进行初始化,因为在控制器内部初始化DbContext违反了SRP,因为这与控制器无关初始化DbContext