Search code examples
asp.net-mvcsimple-injector

MVC Simple Injector and RegisterPerWebRequest


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);
    }
}

Solution

  • Disclosure: I have not used SimpleInjector.

    From what I gather from reading that, no, you don't need to implement IDisposable.

    What it's saying is that, by default, objects that are registered are not disposed of. That is, SimpleInjector won't attempt to call Dispose() if you register the object by means other than per web request.

    However, using RegisterPerWebRequest() means that Dispose() will be called if the object is an IDisposable unless you specify otherwise.