ASP.NET中的选项模式

时间:2019-09-06 04:48:51

标签: c# .net-core configuration

示例我有以下appsettings.json文件

{
  "GrpcClient": {
    // Determine to use Insecure (true) or SSL channel (false)
    "Insecure": false,
    // SSL private key file path
    "PrivateKeyFilePath": "App_Data/Certs/client.key",
    // SSL certificate file path
    "CertificateFilePath": "App_Data/Certs/client.crt",
    // Certificate Authority certificate file paths (separate by semicolon)
    "RootCertificateFilePaths": "App_Data/Certs/messaging-ca.crt",
    // Maximum number of retry attempts for gRPC call
    "RetryCount": 5
  },
  //... there are other settings
}

这是我的C#课程:

public class ServiceConfig 
{
    public GrpcClientSettings GrpcClientSettings { get; set; }
    // and few other properties, map to other settings
}

这是我的启动代码:

private void ConfigureSettings(IServiceCollection services)
{
    services.Configure<ServiceConfig>(Configuration);
    services.AddSingleton(resolver => resolver.GetRequiredService<IOptions<ServiceConfig>>().Value);

    services.AddSingleton<IValidatable>(resolver => resolver.GetRequiredService<IOptions<ServiceConfig>>().Value);
    services.AddTransient<IStartupFilter, ValidationStartupFilter>();
}

您会看到在设置文件中,我的json节点是“ GrpcClient”,但我的C#代码中的属性是“ GrpcClientSettings”(在ServiceConfig类中)。我仍然想保留它(名称约定很少),但是我需要做些额外的代码吗?

1 个答案:

答案 0 :(得分:0)

参考Options post-configuration

  

使用IPostConfigureOptions<TOptions>设置后配置。在完成所有IConfigureOptions<TOptions>配置之后,将运行后配置:

services.Configure<ServiceConfig>(Configuration);
services.PostConfigure<ServiceConfig>(myOptions => {
    var settings = Configuration.GetSection("GrpcClient").Get<GrpcClientSettings>();
    myOptions.GrpcClientSettings = settings;
});