1

I have a class with a method performing some database actions.
I want to allow an existing (open) context to be sent in the method call to be used for the database access.
However if a context is not sent, I create a new one.

I just want to make sure the object is not disposed if included in the method call.

Is the object disposed when a using-scope is used in the called method?

// 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);
    }
}
3
  • 1
    Is dbService disposed here? Yes, leaving the using statement took care of that for you. Commented Apr 19, 2016 at 14:45
  • 1
    using calls Dispose(). If you don't want Dispose() to be called, don't use a using statement. Commented Apr 19, 2016 at 14:45
  • Dispose is called when you reach the closing bracket of the using statement, as you are not wishing for automatic disposal just remove the using statement and do it manually with existingContext.Dispose when you are ready Commented Apr 19, 2016 at 14:49

2 Answers 2

9
// Is dbService disposed here?

Yes, it is disposed. This is a case where optional arguments work against you - better to have two specific overloads:

class DbService
{
    public void SomeDbAction(SomeDbContextObject backendContext)
    {

            // Some actions using the context

    }
    public void SomeDbAction()
    {
        using (var context = CreateNewContextObject())
        {
            SomeDbAction(context);
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

2

You should not dispose of the backendContext object if it has been passed in, but should do so if you created it in the method:

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
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.