Dependency injection with Unity: Lifetime managers

Unity container is a lightweight dependency injection container. It manages creation and resolution of objects that we registered based on life time that we specified.

Here is a list of lifetime managers that exist in Unity.

TransientLifetimeManager 

When you register a type in configuration, or by using the RegisterType method, the default behavior is for the container to use a transient lifetime manager.

For this lifetime manager Unity creates and returns a new instance of the requested type for each call to the Resolve or ResolveAll method. This lifetime manager is used by default for all types registered using the RegisterType.

ContainerControlledLifetimeManager

When you register an existing object using the RegisterInstance method, the default behavior is for the container to take over management of the lifetime of the object you pass to this method using the ContainerControlledLifetimeManager.

Registers an existing object as a singleton instance. For this lifetime manager Unity returns the same instance of the registered type or object each time you call the Resolve or ResolveAll method or when the dependency mechanism injects instances into other classes.

HierarchicalLifetimeManager

Works like ContainerControlledLifetimeManager, the only difference is that when there are child containers, each child resolves its own instance of the object and does not share one with the parent.

PerResolveLifetimeManager

Behavior is like a TransientLifetimeManager, but also marking the type so that instances are reused across the build-up object graph.

PerThreadLifetimeManager

Unity returns, on a per-thread basis, the same instance of the registered type or object each time you call the Resolve or ResolveAll method or when the dependency mechanism injects instances into other classes. This lifetime manager effectively implements a singleton behavior for objects on a per-thread basis.

PerThreadLifetimeManager returns different objects from the container for each thread. If you registered a type mapping using configuration or using the RegisterType method, Unity creates a new instance of the registered type the first time the type is resolved in a specified thread, either to answer a call to the Resolve or ResolveAllmethod for the registered type or to fulfill a dependency while resolving a different type. Subsequent resolutions on the same thread return the same instance.

PerRequestLifetimeManager

Commonly used in web applications. Container will simply resolve the same one instance of the object in http request. So in different http requests will be different resolved objects.

Share this post:Tweet about this on TwitterShare on Facebook0Share on LinkedIn0Share on Google+0Share on Reddit0Email this to someoneDigg this