Unity 2.0:
By default RegisterInstance uses the ContainerControlledLifetimeManager. When the Unity container is disposed, it calls Dispose on the instance (if IDisposable).
In my case that's not what I want. The instance is owned by and disposed by another class; Unity should just inject the reference. So I used:
container.RegisterInstance(instance, new ExternallyControlledLifetimeManager());
The Unity documentation (under Understanding Lifetime Managers) states:
Using the RegisterInstance method to register an existing object results in the same behavior as if you just registered the lifetime container with RegisterType. Therefore, it is recommended that you do not use the RegisterInstance method to register an existing object when using the non-default lifetime managers except for the thread in which the RegisterInstance was invoked.
What does this mean?
The same section also states:
If you registered an existing instance of an object using the RegisterInstance method, the container returns the same instance for all calls to Resolve or ResolveAll or when the dependency mechanism injects instances into other classes, provided that one of the following is true:
- You have specified a container-controlled lifetime manager
- You have used the default lifetime manager
- You are resolving in the same context in which you registered the instance when using a different lifetime manager.
I tried resolving in a different thread after using RegisterInstance with ExternallyControlledLifetimeManager, and it worked - I got the singleton instance.
My code matches an example in the Creating Instance Registrations section. I want to make sure I understand the context caveats, though.
To be clear, I always want the Unity container to inject the instance I registered regardless of thread, etc. and I do not want Unity to dispose of it. Am I doing this correctly?