下面的代码示例来自于Startup.cs文件中Asp.Net Core的
我首先注册了一个名为
如何最优雅地访问
如果可能的话,我更愿意避免在
ConfigureServices
方法。我首先注册了一个名为
AppState
的单例服务。随后,我配置了OpenIdConnect,在OnTokenValidated
lambda内部,我需要访问DI容器中刚刚注册的AppState
服务。如何最优雅地访问
AppState
服务实例?如果可能的话,我更愿意避免在
ConfigureServices
方法内调用services.BuildServiceProvider()
。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();
}
};
}
});