How can you force Unity to Create a new instance?
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
Comments
-
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 over 11 yearsWhich lifetime manager you are using? also, you want to dispose un-managed object?
-
Andy Clark over 11 yearsI have not configured a lifetime manager, I need to dispose my repository objects
-
cuongle over 11 yearswhy do you know that your repository object is not disposed?
-
Andy Clark over 11 yearsIf 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 over 11 yearsI 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 over 11 yearsThis is working, but now when I implement this in my WCF app it is not disposing any objects, any ideas?
-
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.