Andy Clark
Andy Clark

Reputation: 3523

How can you force Unity to Create a new instance?

Using 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 WCF context?

Upvotes: 10

Views: 13792

Answers (2)

StuartLC
StuartLC

Reputation: 107277

Using RegisterType without a LifetimeManager should inject a new instance of the type every time it is injected

From MSDN:

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

Upvotes: 2

cuongle
cuongle

Reputation: 75316

Lifetime Manager in Unity is all what you need. By default, Unity use TransientLifetimeManager:

TransientLifetimeManager. 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, method unless you specify a different lifetime manager.

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

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

Upvotes: 11

Related Questions