[英]Resolving instances with ASP.NET Core DI from within ConfigureServices
[英]How to access a service added to DI container from inside Asp.Net Core's ConfigureServices method
下面的代碼示例來自 Startup.cs 中的 Asp.Net Core ConfigureServices
方法。
我首先注冊了一個名為AppState
的 singleton 服務。 之后,我正在配置 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();
}
};
}
});
使用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();
//...
}
};
});
您可以從事件上下文訪問 DI 服務:
services.AddSingleton<AppState>();
services.Configure<OpenIdConnectOptions>(AzureADB2CDefaults.OpenIdScheme, options =>
{
options.Events = new OpenIdConnectEvents
{
OnTokenValidated = async ctx =>
{
var appState = (AppState)ctx.HttpContext.RequestServices.GetService(typeof(AppState));
appState.DoSomething();
}
};
});
調用services.Configure<T>
,將IConfigureOptions<T>
添加到調用您的操作方法的服務容器中; https://github.com/aspnet/Options/blob/master/src/Microsoft.Extensions.Options/OptionsServiceCollectionExtensions.cs#L72
您可以定義自己的IConfigureOptions<T>
實現並注入您喜歡的任何服務。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.