Unity and TransientLifetimeManager

This is a small question, just to make sure I understand Unity correctly.

I use Unity in an ASP.NET MVC application and I registered the following type:

container.RegisterType<IPizzaService, PizzaService>(); 

And I use it in the controller, for example:

 public class PizzaController : Controller { private IPizzaService _pizzaService; public PizzaController(IPizzaService pizzaService) { _pizzaService = pizzaService; } [HttpGet] public ActionResult Index() { var pizzasModel = _pizzaService.FindAllPizzas(); ... } } 

Each time a page request is executed, a new instance of IPizzaService is introduced and used. So it all works great.

My question is: do I have to do anything special to destroy this instance? I assume that after the request is complete, the controller will be deleted and the PizzaService instance will eventually receive garbage collection.

If I need deterministic deletion of an instance because it uses the context of the entity framework or an unmanaged resource, for example, I need to override the Dispose of the controller, and make sure that I invoke the instance utility myself.

Right? If not, explain why :)

Thanks!

+5
source share
1 answer

IMO, regardless of what the one-time object creates, is responsible for deleting it. When the container enters a one-time object through RegisterType<I, T>() , I want to ensure that the object is ready for use. However, using RegisterInstance<I>(obj) will automatically delete your object.

This can be tricky with an IOC container, and impossible with Unity out of the box. However, there is some really great code 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 DisposingTransientLifetimeManager and DisposingSharedLifetimeManager. Using extensions, the container calls Dispose() on your disposable objects.

One caveat is that you will need to specify the correct (older) version of Microsoft.Practices.Unity.Configuration.dll and Microsoft.Practices.Unity.dll.

+1
source

Source: https://habr.com/ru/post/1205853/


All Articles