I have an issue been working on for a few hours with little progress. I have a need for creating services based off a dynamic configuration. IE lets say I have 5 classes that inherit from IHostedService and they can easily be started using services.AddHostedService<classname>(). The issue I have however is I need to be able to dynamically setup these services. IE:
public static void Register(IServiceCollection services, IConfiguration configuration) { foreach (var service in configuration.GetSection("services").GetChildren()) { foreach (var consumer in service.GetChildren()) { var className = configuration.GetValue<string>("className"); var assemblyName = configuration.GetValue<string>("assemblyName"); System.Type classType = System.Type.GetType(className + ", " + assemblyName); services.AddHostedService<classType>(); } } }
settings file would look like this
{"services": {"service1": {"className": "class.name.something","assemblyName": "test.assembly", },"service2": {"className": "some.other.class.testing","assemblyName": "something.assembly", },"service3": {"className": "this.is.path.to.class.in.assembly","assemblyName": "test.something", } } }
The problem I have is:
services.AddHostedService<classType>();
that is not valid syntax, I cant seem to figure out how to dynamically provide a class type to AddHostedService, it appears you have to use a concrete class.
any ideas? thanks!