Search code examples
c#asp.net-web-apiasp.net-web-api2idisposable

Controllers and IDisposable


If I make a controller implement IDisposable, I assume that the Dispose method still won't be invoked by the GC. So that means I would have to add:

public void Dispose()
{
    Dispose(true);
    GC.SuppressFinalize(this);
}

protected override void Dispose(bool disposing)
{
    if (!isDalDisposed)
    {
        isDalDisposed = true;
        if (disposing)
            DAL.Dispose();
    }
    base.Dispose(disposing);
}

I have read that using Object.Finalize is bad practice and should be avoided where possible.

The issue I have is that my "services" are created in the default constructor which does not permit me to use a using statement to control the lifetime of each service. So, what would be the correct way to handle this issue?


Solution

  • Web API's ApiController has already implemented IDisposable and provides convenient virtual method for developers to override, which is the Dispose(bool) method you are using. So all you need to do is remove your own boolean flag and just check only disposing parameter.

    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
            DAL.Dispose();
        }
        base.Dispose(disposing);
    }