有什么好办法可以拿到ServiceProvider
在 AddOpenIdConnect
, 或 稍后在我们完全设置 DI 容器的地方配置 ClientSecret? (例如在 Configure(IApplicationBuilder app)
中)
我们从其他地方获取客户端 secret ,我们喜欢为此使用 DI。
目前我们这样做,但我真的很想删除 services.BuildServiceProvider()
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddOpenIdConnect(AuthenticationScheme, options =>
{
ServiceProvider serviceProvider = services.BuildServiceProvider(); // we like to prevent this
options.ClientSecret = serviceProvider.GetRequiredService<ISecretRetriever>().GetClientSecret();
笔记
对于类似
OnValidatePrincipal
的事件我们可以从 CookieValidatePrincipalContext.HttpContext.RequestServices
得到它使用
services.BuildServiceProvider()
会给出这个警告:warning "Calling 'BuildServiceProvider' from application code results in a additional copy of Singleton services being created"
最佳答案
身份验证的配置系统使用 Options pattern .这意味着以下方法与您的问题中显示的方法具有类似的效果:
services.AddAuthentication()
.AddOpenIdConnect(AuthenticationScheme, options =>
{
// ...
});
services.Configure<OpenIdConnectOptions>(AuthenticationScheme, options =>
{
options.ClientSecret = "ClientSecret";
});
这很有用,因为选项模式 supports DI ,使用类似以下内容:
services.AddOptions<OpenIdConnectOptions>(AuthenticationScheme)
.Configure<ISecretRetriever>((options, secretRetriever) =>
{
options.ClientSecret = secretRetriever.GetClientSecret();
});
访问
Configure
与 DI 一起使用的方法,您必须先调用 AddOptions
.在本例中,Configure
给定一个类型参数,它表示所需的依赖项。这作为第二个参数传递到您的配置回调中,在 OpenIdConnectOptions
之后正在配置的实例。
关于c# - 在没有 BuildServiceProvider() 的情况下在 AddOpenIdConnect 中获取 ServiceProvider,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62438033/