繁体   English   中英

如何从方法主体中提取配置选项并在 Dot Net Core 3.1 中使用配置 class

[英]How to pull configuration options out of method body and use configuration class in Dot Net Core 3.1

菜鸟在这里。 我遵循了 IdentityServer 4 的快速入门。我正在清理代码。 我正在使用网络核心 3.1。 我的 Startup.ConfigureServices 变得拥挤,我想清理它并将配置选项、值放入 class - 就像 IdentityServer 4 对 IdentityResources、ApiScopes、ApiResources 和 Client 配置选项使用 class 一样。

我已经阅读了许多博客文章,并且从https://andrewlock.net/avoiding-startup-service-injection-in-asp-net-core-3/如何将配置添加到自定义服务的 IoC 容器中看到,但是我还没有找到一种方法来提取框架服务的选项/值,例如 Identity Core 或services.AddAuthentication().AddOpenIdConnect()


    services.AddAuthentication(options =>
    {
      options.DefaultScheme = "Cookies";
      options.DefaultChallengeScheme = "oidc";
    })
    .AddCookie("Cookies", options =>
    {
      options.AccessDeniedPath = "/account/denied";
    })
    .AddOpenIdConnect("oidc", options =>
    {
        /***  HOW DO I PUT THE BELOW KEY/VALUES INTO A CONFIG CLASS  ***/

        options.Authority = "https://demo.identityserver.io";
        options.ClientId = "server.hybrid";
        options.ClientSecret = "secret";
        options.ResponseType = "code id_token";
 
        options.SaveTokens = true;
                    
        options.Scope.Clear();
        options.Scope.Add("openid");
                    
        options.TokenValidationParameters = new TokenValidationParameters
        {
            NameClaimType = "name", 
            RoleClaimType = "role"
        };
    });

并像这样使用该配置 class


var builder = services.AddIdentityServer()
    .AddInMemoryIdentityResources(Config.IdentityResources) <-- From the Config class
    .AddInMemoryApiScopes(Config.ApiScopes) <-- From the Config class
    .AddInMemoryClients(Config.Clients); <-- From the Config class

因此,如果我的问题不清楚,我该如何制作 Config class 并将 class 传递给.AddOpenIdConnect(MyConfigClass)以清理 ConfigureServices 方法(IoC 容器?)

上面的代码是在 IoC 容器中配置服务的最佳/最干净的方式吗? 是我在 Andrew Lock 的博客文章中寻找的答案,我只是不明白吗? 我假设我可以像使用 IS4.AddInMemoryIdentityResources 一样将 class 传递到 .AddOpenIdConnect 扩展方法中

感谢您的帮助。

所有 Microsoft 服务都遵循相同的选项模式 首先,您可以将那些 lambda 方法移动到 static 方法,可能在不同的类上。 这似乎是您的Config示例所做的。 您只需要确保您的 static 方法具有相同的 function 签名。

例如, .AddAuthenticationAction<AuthenticationOptions>委托作为参数。 因此,可以改为传入任何static void foo(AuthenticationOptions o)方法。

或者您可以编写实现IConfigureOptions<T>的服务并注册它们。 如果您需要访问其他服务(例如数据库)以配置这些选项类型,这将特别有用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM