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" } ] } }