locked
Json configuration with polymorphic array RRS feed

  • Question

  • Is it possible to have a polymorphic array setup by json configuration?

    E.g. the following code (all in one file only for the demo of course):

    using Microsoft.Extensions.DependencyInjection;
    using Microsoft.Extensions.Hosting;
    using Microsoft.Extensions.Logging;
    using Microsoft.Extensions.Options;
    using System.Threading;
    using System.Threading.Tasks;
    
    namespace PolymorphicConfigurationArray
    {
        public class Program
        {
            public static void Main(string[] args)
            {
                CreateHostBuilder(args).Build().Run();
            }
    
            public static IHostBuilder CreateHostBuilder(string[] args) =>
                Host.CreateDefaultBuilder(args)
                    .ConfigureServices((hostContext, services) =>
                    {
                        services.Configure<ApplicationOptions>(hostContext.Configuration.GetSection("Application"));
                        services.AddHostedService<Worker>();
                    });
        }
        public class Worker : BackgroundService
        {
            private readonly ILogger<Worker> _logger;
    
            public Worker(ILogger<Worker> logger, IOptions<ApplicationOptions> options)
            {
                _logger = logger;
                logger.LogInformation($"Configuration Description {options.Value.Description}");
            }
    
            protected override async Task ExecuteAsync(CancellationToken stoppingToken)
            {
                while (!stoppingToken.IsCancellationRequested)
                {
                    //_logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
                    await Task.Delay(1000, stoppingToken);
                }
            }
        }
        public class ApplicationOptions
        {
            public string Description { get; set; }
            public ConfigItem[] Items { get; set; }
        }
        public class ConfigItem
        {
            public string ItemName { get; set; }
        }
        public class ConfigItemWithValue : ConfigItem
        {
            public double ItemValue { get; set; }
        }
    }
    

    The json file below may be used to intantiate the ApplicationOptions class with some ConfigItems in the Items array, however, I cannot see any way to get the derived ConfigItemWithValue class from configuration and thus having the Items array as a polymorphic array.
    Is this simply the limitation of json (key/value)?

    I know that newtonsoft.json may serialize/deserialize such a graph by some typename options, is this possible to use in any way for configuration (without a lot of custom code of course)

    {
      "Logging": {
        "LogLevel": {
          "Default": "Information",
          "Microsoft": "Warning",
          "Microsoft.Hosting.Lifetime": "Information"
        }
      },
      "Application": {
        "Description": "Wondering how to achieve polymorphic array with json configuration",
        "Items": [
          { "ItemName": "Name1" },
          { "ItemName": "Name2" }
        ]
      }
    }
    

    Saturday, May 30, 2020 9:27 AM

All replies

  • Hi EuroEager,

    Thank you for posting here.

    I note that your code is more related to ASP.NET Core, so you can consider posting your question in ASP.NET Core forum for more efficient responses.

    Thank you for your understanding.

    Best Regards,

    Xingyu Zhao


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Monday, June 1, 2020 8:30 AM