Question

How do you automatically dispose a class that implements IDisposable that was newed through DI using Unity as the IoC?

For example, say I have an MVC application with the following layers:

  1. MVC
  2. Service
  3. Repository (Entity Framework that implements Unit of Work pattern for CRUD operations)

A UnitOfWork class within the repository layer implements the IDisposable interface and is injected into the service layer using DI via Unity. Unless I am missing something, without automatically disposing the UnitOfWork class you would need to override the Dispose() method on the controller that called the service (which also needs to implement IDisposable), and bubble up through the stack until you reached the Dispose() method on the UnitOfWork (or the respective repository if you weren't using the Unit of Work pattern).

e.g.

// controller
protected override void Dispose(bool disposing)
{
    if (_serviceLayer != null)
    {
        _serviceLayer.Dispose();
    }
    base.Dispose(disposing);
}

// service layer
public override Dispose() {
    if (_uow != null)
    {
        _uow.Dispose();
    }
}

// unit of work
public void Dispose() {
    if (_context != null)
    {
        _context.Dispose();
    }
}

This thread suggests it’s not supported? "There are only a few circumstances where Unity will dispose an instance. It is really unsupported" Is this still true with Unity 3.0.

Was it helpful?

Solution

If you are using Unity bootstrapper for ASP.NET MVC's PerRequestLifetimeManager then at the end of the HTTP request the UnityPerRequestHttpModule will dispose of all objects registered with a PerRequestLifetimeManager that implement IDisposable.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top