I am developing a MVC 5 internet application. I have the following method in my controller:
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
If I have a service class in this controller, that uses the same db
object, do I need to have a Dispose()
method in this service class, or does the Dispose()
method in the controller take care of this?
Thanks in advance.
Generally: The class should dispose of any disposables it is responsible for. Responsibility essentially boils down to whether it "owns" the dependency. In other words, if it's a field on that class and that class instantiates it, then it should also dispose of it.
In the case of your service, while there's likely a field for the context on the service class, you're injecting the context into the service through the constructor, rather than having the service instantiate it. Therefore, it would not be appropriate for the service to dispose of the context, because it does not "own" it.
Further, if you were to employ a dependency injection container, such that the controller no longer instantiates the context, but rather just has it injected into its constructor, then you should also not dispose of it in the controller. The DI container would ultimately be responsible for the disposal.