CA2202 CA2215 HttpApplication Dispose base call

332 views Asked by At

I am currently getting the CA2202 (Do not dispose objects multiple times) on code that I am analysing. The warning refers to HttpApplication.Dispose method that I am overriding. I know the IDispose.Dipose method should not be virtual or be overriden but this a result of Microsoft implementing the IDispose.Dispose as virtual in the HttpApplication class and not providing a virtual protected Dispose method.

The warning appears to be complaining about the calling of the base.Dispose method. I am calling the base Dispose method in case the base class needs to close or dispose of any objects. And also suspect that I'll probably end up with the CA2215 (Dispose methods should call base class dispose) warning otherwise.

Does anyone know why I am getting this (CA2202) warning and what to do about it?

I am tempted to suppress it but the MSDN docs says that it should never be suppressed.

The sub class looks like the following (it has been shortened for brevity and you can assume that the _container field has been initialised):

public class MyHttpApplication : HttpApplication
{
    private bool _disposed;
    private IDisposable _container;

    public sealed override void Dispose()
    {
        if (_disposed)
            return;
        try
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
        finally
        {
            //The following lines is what causes the CA2202 code analysis warning
            base.Dispose();
        }

    }

    protected virtual void Dispose(bool disposing)
    {
        if (_disposed)
            return;

        try
        {
            if (disposing && _container != null)
            {
                _container.Dispose();
            }
        }
        finally
        {
            _disposed = true;
        }
    }   
}
1

There are 1 answers

0
Glen Stone On

It seems there's no way out without suppressing something. My solution was to put the call to base.Dispose() inside the Dispose(bool) method then suppress CA2215, for which the MSDN docs say "It is safe to suppress a warning from this rule if the call to base.Dispose occurs at a deeper calling level than the rule checks."

[SuppressMessage("Microsoft.Usage", "CA2215:Dispose methods should call base class dispose", Justification = "base.Dispose() is called from Dispose(bool)")]
public sealed override void Dispose()
{
    if (_disposed)
        return;
    Dispose(true);
    GC.SuppressFinalize(this);
}

protected virtual void Dispose(bool disposing)
{
    if (_disposed)
        return;

    try
    {
        if (disposing)
        {
            base.Dispose();
            if (_container != null)
            {
                _container.Dispose();
            }
        }
    }
    finally
    {
        _disposed = true;
    }
}