container icon indicating copy to clipboard operation
container copied to clipboard

IDisposable in Unity Container

Open ENikS opened this issue 5 years ago • 0 comments

IDisposable

The primary use of IDisposable is to properly handle instances controlled by the container and allow Garbage Collector to collect them when the container goes out of scope.

Pattern

When the container resolves an instance of a type, the lifetime of that instance is controlled by the LifetimeManager associated with the type. The container recognizes the following variations:

  • Not controlled by the container
  • Controlled by the container but instance is not IDisposable
  • Controlled by the container and implementing IDisposable

Not Controlled by the container

These instances are not tracked or referenced by the container. Once resolved, the lifetime of these objects is up to outside code.

Controlled by the container but instance is not IDisposable

Instances that are controlled by the container, those with ContainerControlledLifetimeManager manager, for example, but not implementing IDisposable are referenced by the container until the container is collected by the GC.

Instances implementing IDisposable

Instances implementing IDisposable are disposed of by calling IDisposable.Dispose() on each of them when the container is disposed of.

Problems

Discarding the container without explicitly calling IDisposable.Dispose()

The current implementation of UnityContainer does not implement a finalizer. As a result, when the container is discarded without explicitly calling IDisposable.Dispose(), all the container-controlled objects are collected along with the container but call to IDisposable.Dispose() on each of them never happens.

After disposing of the container, it can still resolve objects

In scenarios where hierarchies of containers are used to resolve objects, it is possible to dispose parent container and still use the child container to resolve dependencies. In cases where the parent container held singletons, created dependencies are nondeterministic.

Solution

Finalizer:

Adding finalizer and properly implementing IDisposable pattern should remedy the issue of leaked resources.

The Exception

Throwing ObjectDisposedException should resolve issues of nondeterministic dependencies in container hierarchies. Once the container is disposed of, neither the container nor any of its children will be able to resolve any objects.

ENikS avatar Dec 14 '20 01:12 ENikS