How can you force Unity to Create a new instance?

13,377

Solution 1

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()); 

Solution 2

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

Share:
13,377
Andy Clark
Author by

Andy Clark

Software Developer

Updated on July 19, 2022

Comments

  • Andy Clark
    Andy Clark almost 2 years

    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?

    • cuongle
      cuongle over 11 years
      Which lifetime manager you are using? also, you want to dispose un-managed object?
    • Andy Clark
      Andy Clark over 11 years
      I have not configured a lifetime manager, I need to dispose my repository objects
    • cuongle
      cuongle over 11 years
      why do you know that your repository object is not disposed?
    • Andy Clark
      Andy Clark over 11 years
      If I manually update the database it is not reflected in Entity Framework, also I have included a line in the Dispose method to log the fact he method is called in a text file and the log is not being created
    • cuongle
      cuongle over 11 years
      I got it, well, Unity does not support to call Dispose for you,it just release the reference, and let GC to collect. Most of IoCs, you need to manually do disposing
  • Andy Clark
    Andy Clark over 11 years
    This is working, but now when I implement this in my WCF app it is not disposing any objects, any ideas?
  • StuartLC
    StuartLC over 11 years
    @AndyClark clark - We are also using Unity 2.1.505, EF 4.3.1 with a repository pattern, under a WCF service layer, also with config setup. One difference could be that we are using a WCF service behaviour to bootstrap? rafatolotti.wordpress.com/2010/09/12/wcf-unity-app-block.