I have a simple wrapper for the Unity IoC container (temporarily using the Service Locator [anti-] template to inject DI into an outdated codebase), and since IUnityContainer
in Unity implements IDisposable
, I wanted to expose this also through the wrapper.
The wrapper is quite simple:
public class IoCContainer : IIoCContainer { private IUnityContainer _container; public IoCContainer(IUnityContainer container) { _container = container; } public T Resolve<T>() { return _container.Resolve<T>(); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } ~IoCContainer() { Dispose(false); } protected virtual void Dispose(bool disposing) { if (disposing) if (_container != null) { _container.Dispose(); _container = null; } } }
IIoCContainer
is a domain interface on which there is nothing but T Resolve<T>()
, and, of course, IDisposable
. So, everything below this method is just an implementation of IDisposable
as I found it on MSDN .
However, when .Dispose()
is called on this object (for example, when exiting from the using
block), a StackOverflowException
is StackOverflowException
. Debugging, it looks like the call stack repeats between:
Dispose()
is called in this class- What causes
Dispose(true)
in this class - What causes
Dispose()
on an IUnityContainer
- What causes
Dispose()
in this class

I can resolve this in this case by placing the bool
flag in the class, setting it to the first line of Dispose()
and checking it in Dispose(bool)
, so the recursion ends in the second iteration. But why does this happen in the first place? I can only assume that I either missed something obvious or misunderstood something about recycling resources. But what?
David source share