-
Notifications
You must be signed in to change notification settings - Fork 3
Lifetime Managers
Isaac Abraham edited this page Jan 26, 2016
·
2 revisions
One of the main features of any IoC container is to externalise the control of the _lifetime _of an object. In Unity, this is known as a LifetimeManager.
To apply a specific type of Lifetime Manager onto an interface, simply decorate it with the CustomLifetimeManager attribute: -
// The implementation of IMyService will be bound to the HierarchicalLifetimeManager.
[CustomLifetimeManager(typeof(HierarchicalLifetimeManager))]
public interface IMyService { }
As it is so common, if you wish, you can quickly mark an interface as a Singleton, which will instruct the Automapper to register the mapping using Unity's ContainerControlledLifetimeManager
, which in effect acts as a Singleton.
// Attributes
[Singleton]
public interface IMyService { }
public class MyService : IMyService { }
// Fluent
AutomapperConfig.Create()
.AndMapAsSingleton(typeof(IMyService))
var a = container.Resolve<IMyService>();
var b = container.Resolve<IMyService>();
// Custom lifetime managers
AutomapperConfig.Create()
.AndMapWithLifetimeManager<HierarchicalLifetimeManager>(typeof(IYourService));
// a and b are the same object.
Note that this customisation operates only over interfaces.