Reputation: 13531
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!
Upvotes: 7
Views: 5119
Reputation: 664
ContainerControlledTransientManager
was added in Unity
on Jan 11, 2018
Add container 'owned' transient lifetime manager ContainerControlledTransientManager #37
So,
ContainerControlledTransientManager
is required. This lifetime manager is the same asTransientLifetimeManager
except if the object implementsIDisposable
it will keep strong reference to object and dispose it when container is disposed. If created object is not disposable, container does not maintain any object references so when that object is released GC will collect it immediately.
Upvotes: 0
Reputation: 3082
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.
Upvotes: 1