Probably a Unity beginner's question: when using Unity, would you still need to implement Dispose methods on the objects you have injected? Or is even this not needed (so, done automatically by Unity)? This is in the context of a web application.
3 Answers
Implementing IDisposable
has nothing to do with Unity. You should implement the interface when your type is using unmanaged resources likes Files, that cannot be garbage collected by the CLR.
Unity can manage the lifetime of your types and instances. For this case Unity provides diffrent types of LifeTimeManager to control the lifetime of your instances.
Unity does only respect the IDisposable
interface when you register them using the ContainerControlledLifetimeManager
or the HierarchicalLifetimeManager
. That meens when you dispose the Unity-Container it will also call Dispose
on all instances implementing the IDisposable
interface registered by the named LifetimeManager above.
When you register types that implement the IDisposable
interface using the TransientLifetimeManager
(you get a new instances each type you call Resolve on the container), it is up to you to call Dispose
on the instance.

- 34,674
- 10
- 123
- 155
-
1"it is up to you" So, when am I supposed to call it? – Mikhail Orlov Sep 29 '14 at 14:06
-
1@MikhailOrlov you call Dispose on the object, when you have finished work on it and you do not need it anymore. – Jehof Sep 30 '14 at 10:32
-
3no, the question is - when to call Dispose on non-singleton objects? Unity doesn't do it by itself. I ended up using Autofac which has explicit notion of scopes, so anyway. – Mikhail Orlov Oct 01 '14 at 12:36
-
7With regards to manually calling `Dispose`: what if you `Resolve` an object which itself takes dependencies on `IDisposable` objects? You have no way of finding those objects when you don't need it any more. And on top of that, manually calling `Dispose` means you have to be _sure_ that it's been registered with a `TransientLifetimeManager` - if it changes to a different lifetime in the future, you're disposing shared/singleton objects which may be in use elsewhere. – Philip C Sep 01 '16 at 16:15
To extend on what Jehof said, ContainerControlledLifetimeManager
and HierarchicalLifetimeManager
both will call .Dispose()
on the class if it supports it. However, a interesting fact is only the concrete implementation needs to implement IDisposable
, the interface you are mapping does not. Here is a simple example program to demonstrate.
using System;
using System.Threading;
using Microsoft.Practices.Unity;
namespace ConsoleApplication
{
internal class Program
{
private interface IFoo
{
}
private class Foo : IFoo, IDisposable
{
public Foo()
{
Console.WriteLine("Foo Created");
}
public void Dispose()
{
Console.WriteLine("Foo.Dispose() called");
}
}
private class Bar
{
public Bar(IFoo foo)
{
}
}
private static void Main()
{
LifetimeManager manager;
Console.WriteLine("Choose a lifetime manager to test:");
Console.WriteLine(" 1: ContainerControlledLifetimeManager");
Console.WriteLine(" 2: ExternallyControlledLifetimeManager");
Console.WriteLine(" 3: HierarchicalLifetimeManager");
Console.WriteLine(" 4: PerThreadLifetimeManager");
Console.WriteLine(" 5: TransientLifetimeManager");
int choice = int.Parse(Console.ReadLine());
switch (choice)
{
case 1:
manager = new ContainerControlledLifetimeManager();
break;
case 2:
manager = new ExternallyControlledLifetimeManager();
break;
case 3:
manager = new HierarchicalLifetimeManager();
break;
case 4:
manager = new PerThreadLifetimeManager();
break;
case 5:
manager = new TransientLifetimeManager();
break;
default:
return;
}
Console.WriteLine(manager.ToString());
//Use a thread to test PerThreadLifetimeManager's Dispose actions.
var thread = new Thread(() => PerformTest(manager));
thread.Start();
thread.Join();
Console.WriteLine("Press enter to exit...");
Console.ReadLine();
}
private static void PerformTest(LifetimeManager manager)
{
Console.WriteLine("Pre container creation");
using (IUnityContainer container = new UnityContainer())
{
Console.WriteLine("Pre type regrestration");
container.RegisterType<IFoo, Foo>(manager);
Console.WriteLine("Pre bar1 resolve");
var bar1 = container.Resolve<Bar>();
Console.WriteLine("Pre bar2 resolve");
var bar2 = container.Resolve<Bar>();
Console.WriteLine("Leaving container scope.");
}
}
}
}

- 1
- 1

- 124,994
- 33
- 282
- 431
-
1I note in your PerformTest you use 'using' to control the container. If you take away that, then you have to call container.Dispose. I don't think Prism is doing that, which is why I'm not seeing my service dispose being called. – imekon Jun 16 '15 at 15:33
-
@imekon Prism has special rules for when Dispose is called depending on the configuration. Some objects it immediately disposes as soon as they are not visible and some get re-used when you navigate away and then navigate back. – Scott Chamberlain Jun 16 '15 at 16:35
-
The problem I'm seeing is that my service dispose never gets called. Unfortunately this leaves the hardware in a undefined state and the only recovery is a reboot and power cycle the hardware. I've fixed this by doing Container.Dispose() when the application exits. – imekon Jun 17 '15 at 08:01
-
@ScottChamberlain Can you help me with similar question here http://stackoverflow.com/questions/39954586/unitofwork-repository-database-connection-issue?noredirect=1#comment67199903_39954586 – Hiren Desai Oct 29 '16 at 07:08
-
1Updated to net core 3.1 and see output inmediately https://dotnetfiddle.net/GKNw0y – Zaha May 08 '20 at 00:25
Another lifetime manager ContainerControlledTransientManager
that respects IDisposable
was added to 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.

- 594
- 1
- 6
- 18