|Home||Back to Index|
Recently I made a serious error when configuring Unity. I was calling RegisterInstance to register a “Singleton” instance of a class that implemented IDisposable:
There was only one problem: the instance was owned by another class, which was responsible for calling Dispose on it. The Unity container thought it owned the instance, and was disposing of it when the container was disposed. As the owner of the container was also registered as a Singleton, this caused recursive or reentrant Dispose calls.
The fix was simple:
container.RegisterInstance<IFoo>(instance, new ExternallyControlledLifetimeManager());
Be very careful when registering or resolving types that implement IDisposable with Unity (or any IoC Container framework). Be sure you know who owns (holds a strong reference to and is responsible for disposing of) the instances, especially since this can vary depending on how the type or instance was registered.