简体   繁体   中英

ASP.NET Core service scope factory undefined behaviour

I'm observing some peculiar behaviour when getting instances of a service within a background service.

I have a service which is constructed where one of the properties has a default value. For the first two instantiations of this service, it holds the expected default value. On the third instantiation, it consistently has an undefined value.

public class MyWorker : BackgroundService
{
    private readonly IServiceScopeFactory _scopeFactory;
        
    public MyWorker(IServiceScopeFactory scopeFactory)
    {
        _scopeFactory = scopeFactory;
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        for (int i = 0; i < 3; i++)
        {
            using (var scope = _scopeFactory.CreateScope())
            {
                var myService = scope.ServiceProvider.GetRequiredService<MyService>();
                ...
            }

            await Task.Delay(100, stoppingToken);
        }
    }
}
public class MyService
{
    private readonly MyEnum _myEnum;

    public MyService(MyEnum myEnum = MyEnum.ValueA)
    {
        _myEnum = myEnum;
        Console.WriteLine("Value: {0}", myEnum);
    }
}
public class Startup {
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddTransient<MyService>();
        services.AddHostedService<MyWorker>();
    }
}

Output:

Value: ValueA
Value: ValueA
Value: -1140239512

If I add MyService to the container as follows, with explicit instantiation of MyService , the issue disappears:

public class Startup {
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddTransient<MyService>(new MyService());
        services.AddHostedService<MyWorker>();
    }
}

Is anyone aware of what could be causing this behaviour?

This appears to have been a bug that is present in ASP.NET Core 3.x.

The issue is resolved in .NET 5.x.

Refer to this bug report for further info https://github.com/dotnet/extensions/issues/2431

For those interested, a description of why it consistently breaks on the third invocation: https://github.com/dotnet/runtime/issues/42037#issuecomment-691221525

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM