Search code examples
simple-injector

Simple Injector - exiting a Lifetime Scope


I was interested in this statement from the documentation.

For every request within an implicitly or explicitly defined scope, a single instance of the service will be returned and that instance will be disposed when the scope ends.

What actually happens when I exit the using block. If my service is not IDisposable, is it simply that the object stops being cached and is then freed up for GC?

using(container.BeginLifetimeScope())
{
   myServiceThatDoesNotImplementIDisposable; 
}

Thanks


Solution

  • What actually happens when I exit the using block

    When Dispose is called on the scope (what happens when you leave the using block) all disposable components that where cached in that scope are disposed as well and the cache of all created scoped instances (both disposable and not) is cleared. This makes those object eligible for garbage collection.

    Same holds for singletons, although they are scoped around the entire lifetime of the container. They are disposed when the container gets disposed and will get garbage collected when their container instance does.

    Transient instances on the other hand are never tracked by the container. This means they are not stores in a cache. After creation, the container forgets about them immediately.