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?
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);
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With