Reputation: 16310
My controllers reference my services using DI. The controllers have no knowledge of EF or its DbContext. Even the services have no knowledge of EF or the DbContext because they reference UoW (also through DI):
public class CustomerController : ApiController
{
private readonly ICustomerService customerService;
public CustomerController(ILogService logService,
ICustomerService customerService)
{
this.customerService = customerService;
}
}
public CustomerService(ILogService logService, IUnitOfWork unitOfWork) {}
The UoW obviously references the DbContext:
public interface IUnitOfWork : IDisposable { }
public class UnitOfWork : IUnitOfWork
{
private DbContext context;
}
Questions:
Should the UoW implement the IDisposable so that the context is disposed of once the UoW goes out of scope?
Should the services implement IDisposable to dispose of the UoW?
Or is the disposing of UoW and services handled by Autofac (my DI)?
Upvotes: 1
Views: 1314
Reputation: 4130
You always need to clean after yourself so that you take the load off from the garbage collector (GC) and avoid the GC to do the cleaning for you, because it is expensive and needs extra time/resources.
so, if your object is holding a resource and your object doesn't dispose that resource when the object itself is out of scope or get disposed, then this is a memory leak, unless someone else will track that resource and dispose it.
Now depending on which Life-Cycle you registered the services, the Uow and the context with, the DI may call dispose method for your object which mean your object needs to implement IDisposable.
I would implement IDisposable in each, and make sure that I register my service which is the root object, I would register it with the "Instance Per Lifetime Scope" which will create a single instance per http request and will call the service.dispose method at the end of the http request, however, If you registered with "Instance Per Dependency" then you are responsible of disposing the instance which means you need to override the ApiController dispose method and start the dispose cycle from the service down to the context.
Hope that helps.
Upvotes: 0