在后台服务中获取服务实例时,我注意到一些奇怪的行为。
我有一个构造函数中某个属性有一个默认值的服务。前两个服务实例化,它保持了预期的默认值。但是在第三次实例化时,它始终具有未定义的值。
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>();
}
}
输出:
Value: ValueA
Value: ValueA
Value: -1140239512
如果我按照以下方式将
MyService
添加到容器中,并显式实例化MyService
,则问题会消失:public class Startup {
public void ConfigureServices(IServiceCollection services)
{
services.AddTransient<MyService>(new MyService());
services.AddHostedService<MyWorker>();
}
}
有谁知道是什么导致了这种行为?