unitycontainer / microsoft-dependency-injection

Unity.Microsoft.DependencyInjection package
Apache License 2.0
63 stars 36 forks source link

IServiceScopeFactory.CreateScope() => NullReferenceException #83

Open max-ieremenko opened 4 years ago

max-ieremenko commented 4 years ago

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?

ENikS commented 4 years ago

Might be related to this issue