【问题标题】:How do I load a section of config into a custom object using HostBuilder in an Azure WebJob如何在 Azure WebJob 中使用 HostBuilder 将配置部分加载到自定义对象中
【发布时间】:2019-10-21 15:21:06
【问题描述】:

我正在尝试找出我在这个 sn-p 代码中缺少的内容。我正在创建一个希望部署到 Azure 的 Azure WebJob,但我需要将我的 appsettings.json 文件中的一段 JSON 加载到我创建的客户对象中。我似乎没有 GetSection 对象上可用的 GetSection 方法,我不明白我缺少什么,以便我可以将配置的一部分映射到我的 HostOptions 类(POCO 采用配置部分)。

这是我的代码,我使用的是 .NET Core 3.0。

private static void Main(string[] args)
{
    var builder = new HostBuilder()
        .ConfigureWebJobs(config =>
        {
            config.AddTimers();
            config.AddAzureStorageCoreServices();
        })
        .ConfigureAppConfiguration((builderContext, config) =>
        {
            config.AddJsonFile("appsettings.json", optional: true);
            config.AddJsonFile($"appsettings.{builderContext.HostingEnvironment.EnvironmentName}.json", optional: true);
            config.AddEnvironmentVariables();
        })
        .ConfigureServices(services =>
        {
            // Some IoC mappings...
        })
        .Build();

    builder.Run();
}

【问题讨论】:

    标签: c# .net-core azure-webjobs azure-webjobssdk


    【解决方案1】:

    使用IWebHostBuilder.ConfigureServices 的重载

       .ConfigureServices((builderContext, services) => {
            IConfiguration configuration = builderContext.Configuration;
            HostOptions options = configuration.GetSection("MySection").Get<HostOptions>();
    
            services.AddSingleton(options);
    
            // Some IoC mappings...
        })
    

    【讨论】:

      猜你喜欢
      • 2023-03-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多