Search code examples
c#.netentity-frameworkdispose

CA2000 and I don't see the reason


I'm currently writing a project and I use Microsoft Code Analysis and I do receive the following error:

CA2000: Dispose objects before losing scope.

This is on code which I've written around the Entity Framework.

public bool IsInstalled(InstallationContext context)
{
    var dbContext = new ScheduleFrameworkDataContext();
    var repository = new TaskRepository(dbContext);

    try
    {
        // Check if there is already a task with the same name.
        if (repository.Get().Select(x => x.Name == context.InstallationParameters.Name).Any())
        { return true; }
    }
    finally { dbContext.Dispose(); }

    return false;
}

Now, I do think that my context is disposed because it's in the finally block. (The context is a EF Code First DB Context). However, I still receive that error.

Am I missing something here?


Solution

  • The code analysis tool is right in this instance.

    If the TaskRepository() constructor throws, the finally block won't run (since the exception is thrown outside of the try block), and dbContext will not be disposed.

    Moving the constructor call and the assignment to repository inside the try block would suppress the warning.