As per the Simple Injector documentation, I'm instantiating my repository objects for an MVC application as such:
container.RegisterPerWebRequest<IUserRepository, SqlUserRepository>();
container.RegisterPerWebRequest<IOrderRepository, SqlOrderRepository>();
But I've just found the documentation also states:
In contrast to the default behavior of Simple Injector, these extension methods ensure the created service is disposed (when such an instance implements IDisposable).
https://simpleinjector.codeplex.com/wikipage?title=ObjectLifestyleManagement#PerWebRequest
Question: Does this mean when using RegisterPerWebRequest, my objects need to implement IDisposable so they get disposed at the end of the web request (i.e. below code)?
Side-note: I believe using WebRequestLifestyle, RegisterInitializer, RegisterForDisposal, also requires objects implementing IDisposable.
Example code (interface and implementation) below.
public interface IUserRepository : IDisposable
{
...
}
public class SqlUserRepository : IUserRepository, IDisposable
{
...
...
...
private bool disposed = false;
protected virtual void Dispose(bool disposing)
{
if (!this.disposed)
{
if (disposing)
{
_context.Dispose();
}
}
this.disposed = true;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}
IDisposable; only your implementations should. Otherwise you're leaking implementation details and are violating the Dependency Inversion Principle. - Steven