I have followed this post to create a writable options class for .Net Core WebAPI. I use this class for updating my appsettings.json
file.
I want to create these writable options classes dynamically. For example, I have multiple options classes like OptionsA
, OptionsB
and so on. They can be configured in appsettings.json
and should only be injected when they are present in that file.
So far so good, now my problem is ConfigureWritable
has a type parameter T
. My problem is, when my code finds OptionsA
in the appsettings.json
file, how do I supply the type to the ConfigureWritable
method?
Here's what I have so far:
private void AddOptionalServices(IServiceCollection services, ServiceSettings serviceSettings)
{
foreach (var serviceSetting in serviceSettings.Services)
{
var serviceType = AppDomain.CurrentDomain.GetAssemblies().SelectMany(t => t.GetTypes()).Where(t => t.Name == serviceSetting.Name).FirstOrDefault();
var settingsType = (Type)serviceType.GetProperty("ServiceType").GetValue(serviceType, null);
services.AddSingleton(typeof(IHostedService), serviceType);
services.ConfigureWritable<settingsType>(Configuration.GetSection("")); //Problem lies here
}
}
settingsType
is a property that is returned from serviceType.
EDIT: Second attempt based on Lasse's comment:
private void AddOptionalServices(IServiceCollection services, ServiceSettings serviceSettings)
{
foreach (var serviceSetting in serviceSettings.Services)
{
var serviceType = AppDomain.CurrentDomain.GetAssemblies().SelectMany(t => t.GetTypes()).Where(t => t.Name == serviceSetting.Name).FirstOrDefault();
var settingsType = (Type)serviceType.GetProperty("ServiceType").GetValue(serviceType, null);
services.AddSingleton(typeof(IHostedService), serviceType);
var method = typeof(IServiceCollection).GetMethod("ConfigureWritable"); //returns null
var methods = typeof(IServiceCollection).GetMethods(); //returns empty enumeration
var generic = method.MakeGenericMethod(settingsType);
generic.Invoke(this, null);
}
}
As you can see, I don't get the method back when using GetMethod
.