use*_*866 3 c# dependency-injection asp.net-core
下面的代码示例来自ConfigureServicesStartup.cs 中的Asp.Net Core方法。
我首先注册一个名为AppState. 之后,我正在配置 OpenIdConnect,并且在OnTokenValidatedlambda内部,我需要访问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();
}
};
});
Run Code Online (Sandbox Code Playgroud)
编辑:使用下面的答案,我像这样编辑了代码,但我可以确认 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();
}
};
}
});
Run Code Online (Sandbox Code Playgroud)
使用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();
//...
}
};
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
622 次 |
| 最近记录: |