I would like dynamically load and register services in my application. To do that I need to be able to load configuration files from different projects in solution and merge values from them into single json array. Unfortunately by default in ASP.Net Core configuration overrides values.
I register files with following code (part of Program.cs file):
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((webHostBuilderContext, configurationbuilder) =>
{
var env = webHostBuilderContext.HostingEnvironment;
configurationbuilder.SetBasePath(env.ContentRootPath);
configurationbuilder.AddJsonFile("appsettings.json", false, true);
var path = Path.Combine(env.ContentRootPath, "App_Config\\Include");
foreach(var file in Directory.EnumerateFiles(path, "*.json",SearchOption.AllDirectories))
{
configurationbuilder.AddJsonFile(file, false, true);
}
configurationbuilder.AddEnvironmentVariables();
})
.UseStartup<Startup>();
The code searches for all files with *.json extension inside App_Config\Include directory and adds all of them to the configuration builder.
Structure of the files look following way:
{
"ServicesConfiguration": {
"Services": [
{
"AssemblyName": "ParsingEngine.ServicesConfigurator, ParsingEngine"
}
]
}
}
As you can see I have got main section ServicesConfiguration then Services array with objects which have one attribute AssemblyName.
To read those values I use ServicesConfiguration class with list:
public class ServicesConfiguration
{
public List<ServiceAssembly> Services { get; set; }
}
And that list uses ServiceAssembly class:
public class ServiceAssembly
{
public string AssemblyName { get; set; }
}
To load that configuration I use IOptions at constructor level (DI):
Microsoft.Extensions.Options.IOptions<ServicesConfiguration> servicesConfiguration,
And configuration seems to be loaded - but values from files are not merged but overridden by last found file.
Any ideas how to fix that?
List<ServiceAssembly> Servicesyou want, then serialize that again into a json file and callAddJsonpassing it.JSONfiles yourself, parse them into the class and just register that class as a singleton. This way you can do whatever you want with the JSON files and plus you avoid having to use theIOptionspattern which most people (me included) dislike.