我有一个类,其中包含执行某些数据库操作的方法 我想允许在方法调用中发送现有(开放)上下文以用于数据库访问 但是,如果没有发送上下文,我会创建一个新的上下文。
我只想确保在方法调用中包含该对象。
在被调用方法中使用using-scope时是否处置了对象?
// DbService class
class DbService
{
private void SomeDbAction(SomeDbContextObject backendContext = null)
{
using (var context = backendContext ?? CreateNewContextObject())
{
// Some actions using the context
}
}
}
// Call from another class
class Temp
{
void DoSomeThing()
{
var existingContext = new SomeDbContextObject();
dbService.SomeDbAction(existingContext);
// Is dbService disposed here?
UseContextForSomethingElse(existingContext);
}
}
答案 0 :(得分:9)
// Is dbService disposed here?
是的,它被处理掉了。这是一个可选参数对你不利的情况 - 最好有两个特定的重载:
class DbService
{
public void SomeDbAction(SomeDbContextObject backendContext)
{
// Some actions using the context
}
public void SomeDbAction()
{
using (var context = CreateNewContextObject())
{
SomeDbAction(context);
}
}
}
答案 1 :(得分:2)
如果已传入backendContext
对象,则
private void CoreSomeDbAction(SomeDbContextObject backendContext) {
//TODO: Some actions using the context
}
private void SomeDbAction(SomeDbContextObject backendContext = null) {
if (null == backendContext) {
// created context should be disposed
using (SomeDbContextObject context = new SomeDbContextObject(...)) {
CoreSomeDbAction(context);
}
}
else
CoreSomeDbAction(backendContext); // passed context should be prevent intact
}