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);
}
}
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.