Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 947
r3plica Avatar asked Jul 15 '26 03:07

r3plica


2 Answers

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);
}
like image 189
tia Avatar answered Jul 17 '26 17:07

tia


If you can override protected void Dispose(bool disposing), it would imply that the base class uses the Disposable pattern, and already implements IDisposable.

Just remove the IDisposable interface and the public void Dispose() method, and it should work.

like image 29
Markus Jarderot Avatar answered Jul 17 '26 17:07

Markus Jarderot



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!