Unity Life time management
Posted on: January 7, 2013
When you use Unity to get an instance of a class, Unity pass through the life time manager. The life time manager responsibility is indicate to unity how to instance the class into an object. This one may already have an instanced object for the class requested and thus give this one instead of creating a new instance.
TransientLifetimeManager is the default life time manager used by Unity if none is specified. This is the simplest form of life time manager. It creates a new instance every time unity need an instance of the class.
1var container = new UnityContainer(); container2 .RegisterType(typeof(IMyClass), typeof(MyClass), "namedMyClass")3 .RegisterType(typeof(IMyClass), typeof(MyClass), "named2MyClass", new TransientLifetimeManager());
In the above example, you can see two registrations with unity of IMyClass interface with the concrete implementation of MyClass. Both of them are using the
TransientLifetimeManager. The first one is implicit because it use the default life time manager, while the second is explicit by having a third parameters which specify to use
TransientLifetimeManager life time manager.
The singleton is pattern (or anti-pattern) that specify that only one instance will live in memory. With Unity, the singleton life time manager is called
ContainerControlledLifetimeManager will instance on the first call the class into an object and all subsequent call will simply give a pointer (reference) to the same object.
1var container = new UnityContainer(); container2 .RegisterType(typeof(IMyClass), typeof(MyClass), "SingletonMyClass", new ContainerControlledLifetimeManager());
Of course, it's only possible to use the explicit registration for singleton since the implicit would create a
TransientLifetimeManager. A small note before we pass to the next life time manager : if you are using a web application, beware that the object will be shared between all your users.
Others life time manager
Unity does have multiple others life time manager like
PerResolveLifetimeManager. Both of them won't be discuss there. The first one can be useful with a system where you are using parallel operations and the last one in some custom case where the life time manager need to be re-created every time.
In a web application, the default life time,
TransientLifetimeManager, is the one to use. It will create an instance per web request. Of course,
ContainerControlledLifetimeManager is also used in the case of instancing the data access layer, the caching system, the logging system, etc. Those are used across the system without containing "user" objects.