Unity and IDisposable

03/22/11

Unity and IDisposable

Recently I made a serious error when configuring Unity. I was calling RegisterInstance to register a “Singleton” instance of a class that implemented IDisposable:

  container.RegisterInstance<IFoo>(instance);

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

See my Stack Overflow post for important details, especially the excellent article by Ladislav Mrnka on Object lifetime management with Unity.

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.


Your Host: webmaster@truewill.net
Copyright © 2000-2013 by William Sorensen. All rights reserved.