AsyncLocal为什么从类的异步方法设置字段的值时不保留该值。考虑这个例子:
var scope = new TestScope();
// The default value is 0
Console.WriteLine(scope.Counter.Value);
// Setting the vlaue to 2
await scope.SetValueAsync();
Console.WriteLine(scope.Counter.Value);
class TestScope
{
public readonly AsyncLocal<int> Counter = new AsyncLocal<int> { Value = 0 };
public async Task SetValueAsync()
{
this.Counter.Value = 2;
await Task.Yield();
}
}
Run Code Online (Sandbox Code Playgroud)
预期输出应该是:
0
2
但实际情况是:
0
0
为什么退出方法时异步上下文会发生变化SetValueAsync?
我想OnModelCreating在DbContext. 我需要做什么?
我可以通过DbContext构造函数注入服务。但它似乎不够有效,因为该方法在应用程序启动时被调用一次,我必须为它增肥我的整个 DbContext 类。
public PortalContext(DbContextOptions<PortalContext> options, IPasswordService passwordService) : base(options)
{
this._passwordService = passwordService;
}
...
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
...
entity<User>().HasData(
new User
{
UserName = "admin",
Password = this._passwordService.EncryptPassword("passw0rd");
}
);
...
}
Run Code Online (Sandbox Code Playgroud)
上面的代码可以替换为:
public PortalContext(DbContextOptions<PortalContext> options) : base(options)
{
}
...
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
...
var passwordService = GetPasswordService(); // How?
entity<User>().HasData(
new User
{
UserName = "admin",
Password = passwordService.EncryptPassword("passw0rd");
}
);
... …Run Code Online (Sandbox Code Playgroud)