gpt4 book ai didi

c# - 如何从 Asp.Net Core 的 ConfigureServices 方法内部访问添加到 DI 容器的服务

转载 作者:行者123 更新时间:2023-12-04 14:45:15 24 4
gpt4 key购买 nike

下面的代码示例来自 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com