c# - 在没有 BuildServiceProvider() 的情况下在 AddOpenIdConnect 中获取 ServiceProvider

标签 c# asp.net-core dependency-injection openid-connect asp.net-core-3.1

有什么好办法可以拿到ServiceProviderAddOpenIdConnect , 稍后在我们完全设置 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/

相关文章:

javascript - 如何将 C# 变量传递给 JavaScript 函数

c# - SMTP 异常 : Unable to read data from the transport connection: net_io_connectionclosed

c# - 从 .NET Core/ASP.NET Core 中的类库访问应用 key 数据

c# - Xamarin DependencyService : System. MissingMethodException:找不到 [Interface] 的默认构造函数

c# - 具有多个存储库和服务的 .NET MVC Controller ?

c# - Toolstripbutton 不验证文本框

c# - IServiceCollection 不包含 AddHttpClient 的定义

angular - 即使在使用 .NET Core 和 Angular 客户端启用它之后,CORS 错误仍然会发生

asp.net-core - 如何使用 Servicestack 在 .NET Core 中使用 Windows 身份验证登录

java - Spring 中的有状态和无状态 Bean