Reputation: 13367
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?
Upvotes: 3
Views: 2958
Reputation: 4633
Is there any specific reason why you create the service in the constructor?
Since the controller is instantiated per request you can create the service in the action itself within a 'using' block. The lifetime of the service is anways limited to the action.
Upvotes: 1
Reputation: 9698
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);
}
Upvotes: 7
Reputation: 89181
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.
Upvotes: 3