在创建对现有对象的引用时被释放调用



我有一个类,它有一个执行一些数据库操作的方法
我想允许在用于数据库访问的方法调用中发送现有(打开)上下文
但是,如果没有发送上下文,我会创建一个新的上下文。

我只想确保对象在包含在方法调用中时不会被丢弃。

当调用的方法中使用了using作用域时,对象是否已被释放?

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

如果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
}

最新更新