Unity RegisterInstance LifetimeManager overload

Oct 27, 2011 at 12:18 AM
Edited Oct 27, 2011 at 12:18 AM

I am a bit confused that in Unity, there is an overload of RegisterInstance that allows you to specify a LifetimeManager.

Surely if you are registering an instance (i.e. a single object), then the instance will always be a singleton, regardless of the specified lifetime?

Can anyone shed some light on this?

Oct 27, 2011 at 3:59 AM

I recommend reading Understanding Lifetime Managers as well as Creating Instance Registrations.

I think your scenario of registering an instance as a singleton is the desired behavior in the vast majority of situations.  The different lifetime managers allow the behavior to be modified to suit different needs.  For example, if you were using a third party library that supplied you with a singleton instance and you wanted to register that instance with the container your would use the ExternallyControlledLifetimeManager so that the container would hold a weak reference to the object (the object lifetime is managed elsewhere in this case).  

Randy Levy
Enterprise Library support engineer