Skip to content

IServiceScopeFactory.CreateScope() => NullReferenceException #83

Description

@max-ieremenko

Hi, i am trying to implement this suggestion "Do not capture services injected into the controllers on background" from microsoft docs.
It works with default dependecy injection mechanism, but when i switch to UnityServiceProvider the code throws exception:

[ApiController]
[Route("[controller]")]
public class TestController : ControllerBase
{
    private readonly IServiceScopeFactory _serviceScopeFactory;

    public TestController(IServiceScopeFactory serviceScopeFactory)
    {
        _serviceScopeFactory = serviceScopeFactory;
    }

    [HttpGet]
    public string Get()
    {
        Task.Run(DoSomething);

        return "hello";
    }

    private async Task DoSomething()
    {
        await Task.Delay(1000);

        // CreateScope, exception thrown: 'System.NullReferenceException' in Unity.Microsoft.DependencyInjection.dll
        using (var scope = _serviceScopeFactory.CreateScope())
        {
        }
    }
}

The unity container behind Unity.Microsoft.DependencyInjection.ServiceProvider (_serviceScopeFactory) is already disposed, because request is finished.
Is it a bug or how this example should look like?

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions