How to get Unity to create a new instance?

Using the Unity Application block, how can you force the Unity configuration to create a new instance of an object when we call the UnityContainer.Resolve<T>() method in the WCF context?

+7
source share
2 answers

Unity Lifetime Manager is all you need. By default, Unity uses the TransientLifetimeManager :

TransientLifetimeManager. For this time 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 method, unless you specify another life manager.

If you need to use another lifetime manager, simply specify in the Register method:

 var container = new UnityContainer(); container.RegisterType<IMyType, MyType>(new PerResolveLifetimeManager()); 
+9
source

Using RegisterType without a LifetimeManager should introduce a new instance of the type each time it is entered

From MSDN :

If you do not specify a value for the lifetime, the type is registered for a temporary lifetime, which means that a new instance will be created with every call to Resolve

+1
source

All Articles