创建对现有对象的引用时是否调用处置?

Is disposed called when creating a reference to an existing object?

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

我只是想确保如果包含在方法调用中的对象不会被释放。

调用方法中使用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);
    }
}
// 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
}