microsoft-dependency-injection icon indicating copy to clipboard operation
microsoft-dependency-injection copied to clipboard

IServiceScopeFactory.CreateScope() => NullReferenceException

Open max-ieremenko opened this issue 5 years ago • 1 comments

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?

max-ieremenko avatar Sep 10 '20 13:09 max-ieremenko

Might be related to this issue

ENikS avatar Sep 11 '20 16:09 ENikS