Skip to content

Prevent externally provided IServiceScopes from being disposed prematurely. #20

Description

@dotnetjunkie

Simple Injector allows framework dependencies to be resolved (cross wired) by making use of the .AddSimpleInjector and .UseSimpleInjector extension methods. This allows the following:

using (AsyncScopedLifestyle.BeginScope(container))
{
    var sc = container.GetInstance<IServiceScope>();
    sc.ServiceProvider.GetService<SomeScoped>();
}

In this case, the framework's IServiceScope is internally created and cached by the Simple Injector scope and when the Simple Injector scope is disposed of, so will the IServiceScope be with its SomeScoped registation.

But now consider the following example where an already-existing IServiceScope is provided:

using (AsyncScopedLifestyle.BeginScope(container))
{
    container.GetInstance<ServiceScopeProvider>().ServiceScope = serviceScope;

    var sc = container.GetInstance<IServiceScope>();
    Assert.AreSame(serviceScope, sc);
    sc.ServiceProvider.GetService<SomeScoped>();
}

In this case the resolved IServiceScope is the externally provided instance. With the v5.3 integration, however, with the disposal of the Simple Injector scope, that externally provided IServiceScope with its SomeScoped registration are disposed as well.

This last, however, is an error. Since that IServiceScope is externally provided, it is not created by Simple Injector, and Simple Injector should, threrefore, not dispose of it.

This is important, because even though the Simple Injector scope is disposed, the IServiceScope might live on for some time and there might be code that uses some scoped, disposable framework dependency. Such dependency would break.

In the latter case, the externally provided IServiceScope should not be disposed of.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions