本地IdentityServer4通过OpenIdConnect首次访问站点时需要注册一个新用户。找到了在事件中执行此操作的“最佳位置” OnUserInformationReceived,但不确定如何在事件处理程序(启动类)中访问 EF DbContext。没有 DI 用于获取 DbContext 的预配置实例(它在其构造函数中请求其他依赖项)。
public void ConfigureServices(IServiceCollection services)
{
// ...
services.AddAuthentication(options =>
{
options.DefaultScheme = "Cookies";
options.DefaultChallengeScheme = "oidc";
})
.AddCookie("Cookies")
.AddOpenIdConnect("oidc", options =>
{
options.SignInScheme = "Cookies";
// ...
options.Events.OnUserInformationReceived = OnUserInformationReceived;
});
// ...
}
private Task OnUserInformationReceived(UserInformationReceivedContext c)
{
var userId = c.User.Value<string>(JwtRegisteredClaimNames.Sub);
// Call DbContext to insert User entry if doesn't exist.
// Or there is another place to do that?
return Task.CompletedTask;
}
Run Code Online (Sandbox Code Playgroud) 我有像
public interface IEmployeeRepository
{
Task<EmployeeSettings> GetEmployeeSettings(int employeeId);
Task<ICollection<DepartmentWorkPosition>> GetWorkPositions(int employeeId);
}
Run Code Online (Sandbox Code Playgroud)
存储库的构造函数(DbContext 注入):
public EmployeeRepository(EmployeeDbContext dbContext)
{
_dbContext = dbContext;
}
Run Code Online (Sandbox Code Playgroud)
并在 EF Core 2.0 中调用它,例如
var settingsTask = _employeeRepository
.GetEmployeeSettings(employeeId.Value);
var workPositionsTask = _employeeRepository
.GetWorkPositions(employeeId.Value);
await Task.WhenAll(settingsTask, workPositionsTask);
// do other things...
Run Code Online (Sandbox Code Playgroud)
问题:
对于 EF Core 3.0,有 InvalidOperationException:在上一个操作完成之前,在此上下文上启动了第二个操作...
DbContext 在 ConfigureServices 中注册,如
services.AddDbContext<EmployeeDbContext>(ServiceLifetime.Transient);
Run Code Online (Sandbox Code Playgroud)
教程如下:Entity Framework Core 不支持在同一个 DbContext 实例上运行多个并行操作。
但!如何在异步存储库中使用它?