下面的代码示例来自 Asp.Net Core ConfigureServices
Startup.cs 中的方法。
我首先注册一个名为 AppState
的单例服务.之后,我正在配置 OpenIdConnect,并在 OnTokenValidated
里面lambda,我需要访问 AppState
我刚刚在上面的 DI 容器中注册的服务。
访问 AppState
的最优雅方式是什么?服务实例?
我宁愿不打电话 services.BuildServiceProvider()
内ConfigureServices
如果可能的话。
services.AddSingleton<AppState>();
services.Configure<OpenIdConnectOptions>(AzureADB2CDefaults.OpenIdScheme, options =>
{
options.Events = new OpenIdConnectEvents
{
OnTokenValidated = async ctx =>
{
//How to get access to instance of AppState,
//which was added to DI container up above
AppState appState = //{get from DI somehow};
appState.DoSomething();
}
};
});
编辑:使用下面的答案,我像这样编辑了代码,但我可以确认 OnTokenValidated 事件没有触发,而不是我原始问题中的上面的代码,它确实触发了:
services.AddOptions<OpenIdConnectOptions>(AzureADB2CDefaults.OpenIdScheme)
.Configure<IServiceScopeFactory>((options, sp) => {
using (var scope = sp.CreateScope())
{
options.Events = new OpenIdConnectEvents
{
OnTokenValidated = async ctx =>
{
var appState = scope.ServiceProvider.GetRequiredService<AppState>();
await appState.Dosomething();
}
};
}
});
最佳答案
使用 TokenValidatedContext
访问当前请求服务提供者并解析服务
services
.Configure<OpenIdConnectOptions>(AzureADB2CDefaults.OpenIdScheme, options => {
options.Events = new OpenIdConnectEvents {
OnTokenValidated = async ctx => {
//Get access to instance of AppState,
//which was added to DI container up above
AppState appState = ctx.HttpContext.RequestServices
.GetRequiredService<AppState>();
await appState.DoSomething();
//...
}
};
});
关于c# - 如何从 Asp.Net Core 的 ConfigureServices 方法内部访问添加到 DI 容器的服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61003307/