传递给另一个`using`块时,DbContext过早处置 [英] DbContext prematurely disposing when passed into another `using` block

查看:48
本文介绍了传递给另一个`using`块时,DbContext过早处置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个功能需要在多个位置使用的活动 dbContext .在某些地方 DbContext 已经存在,所以我将其传递并使用(如果存在):

I have one function that requires an active dbContext that is used in multiple places. In some places the DbContext already exists so I pass it in and use it if it does:

public void DoStuff(){
     using (var db = new dbContext()){
         DoThings(db);
         db.SaveChanges(); // breaks, context was disposed
     }
  }

public void DoThings(DbContext optionalContext = null){
     using (var db = optionalContext ?? new dbContext()){
         DoInternalThings(db);
     }
  }

是否有任何方法可以使此模式起作用,还是应该只使 optionalContext 成为必需,并从调用函数中调出上下文?因为之后我得到了一堆这样的东西:

Is there any way to make this pattern work, or should I just make the optionalContext required and spin up the contexts from the calling functions? Because then I end up with a bunch of this:

public void DoStuff(){
     using (var db = new dbContext()){
         DoThings(db);
         db.SaveChanges(); // breaks
     }
 }

 public void DoThings(){ // version without dbContext passed in - solely a wrapper - yuck!
     using (var db = new dbContext()){
         DoThings(db);
     }
 }

  public void DoThings(DbContext db){
       DoInternalThings(db);
  }

推荐答案

您不应处置传递给函数的对象,因为您不拥有该对象且无法控制其寿命.是的,在调用函数中旋转上下文并创建所需的上下文,这取决于您如何设计美观而易于使用的方式.

You should not dispose an object that is passed into a function, because you do not own it and don't control its lifetime. Yes, spin up a context in a calling function and makes the context required, and it's up to you how to design that in a beautiful and convenient to use way.

这篇关于传递给另一个`using`块时,DbContext过早处置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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