2
votes

When running code analysis on my MVC3 project that uses Ninject, I receive the following warning:

Warning 1 CA2000 : Microsoft.Reliability : In method 'NinjectMVC3.CreateKernel()', object 'kernel' is not disposed along all exception paths. Call System.IDisposable.Dispose on object 'kernel' before all references to it are out of scope.

I understand I can easily suppress the message but am curious if there is a better way to resolve the warning. The static method is obviously meant to return 'kernel' so one should not dispose of it.

    private static IKernel CreateKernel()
    {
        var kernel = new StandardKernel();
        RegisterServices(kernel);
        return kernel;
    }

Not a major problem, just a learning exercise.

1

1 Answers

2
votes

The problem that CA2000 is detecting here is that the instantiated object will be "orphaned" without disposition if an exception is thrown between its instantiation and its return from the method. In most cases, I would tend to consider the cure to be worse than the problem for such scenarios. However, if you wish to fix it and use of the approach suggested by Darin is not an option, here's an alternate version that should pass CA2000 verification:

private static IKernel CreateKernel()
{
    var kernel = new StandardKernel();
    try
    {
        RegisterServices(kernel);
        return kernel;
    }
    catch
    {
        kernel.Dispose();
        throw;
    }
}