Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Unity, how do you automatically dispose an IDisposable?

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.

like image 929
Mark Erasmus Avatar asked Jan 19 '26 21:01

Mark Erasmus


1 Answers

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.

like image 58
Randy supports Monica Avatar answered Jan 23 '26 04:01

Randy supports Monica



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!