This is a small question, just to make sure I'm understanding Unity correctly.
I'm using Unity in an ASP.NET MVC application, and I have registered a type as follows:
container.RegisterType<IPizzaService, PizzaService>();
And I'm using it in a controller like:
public class PizzaController : Controller
{
private IPizzaService _pizzaService;
public PizzaController(IPizzaService pizzaService)
{
_pizzaService = pizzaService;
}
[HttpGet]
public ActionResult Index()
{
var pizzasModel = _pizzaService.FindAllPizzas();
...
}
}
Every time a page request is done, a new instance of IPizzaService
is injected and used. So this all works fine.
My question: do I have to do anything special to dispose this instance? I assume that, once the request has ended, the controller is disposed and the PizzaService instance eventually gets garbage collected.
If I need deterministic disposal of an instance because it uses an entity framework context or an unmanaged resource for example, I have to override Dispose of the controller, and there make sure I call the dispose of the instances myself.
Right? If not, please explain why :)
Thanks!
IMO, whatever creates a disposable object is responsible for disposing it. When the container injects a disposable object via RegisterType<I, T>()
, I want to guarantee that the object is ready to be used. However, using RegisterInstance<I>(obj)
does dispose of your object automatically.
This can be difficult with an IOC container, and is impossible with Unity out of the box. However, there is some really nifty code out there that I use all the time:
http://thorarin.net/blog/post/2013/02/12/Unity-IoC-lifetime-management-IDisposable-part1.aspx
The blog has code for a DisposingTransientLifetimeManager and DisposingSharedLifetimeManager. Using the extensions, the container calls Dispose()
on your disposable objects.
One caveat is that you'll need to reference the proper (older) version of Microsoft.Practices.Unity.Configuration.dll & Microsoft.Practices.Unity.dll.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With