I am using VS 2017 and .NET Core. Using Dependency Injection, I would like to register my service at runtime, dynamically. My goal is to write instances of my service that implement the service interface inside of separate assemblies. The servicename/assembly name will then be added to some sort of configuration file (or db table).
My registration code would do something like this:
var ServiceTypeName = LoadServiceAssembly(AssemblyName);
var serviceProvider = new ServiceCollection()
.AddTransient<IDILogger, "ConsoleDILogger">() // <--- Goal
.BuildServiceProvider();
var logger = serviceProvider.GetService(IDILogger);
Clearly, the AddTransient line will not work as such a method does not exist. It does, however, depict the idea. I want to register the type by a string name so that the loader application need not be recompiled everytime I add a new service type.
I cannot seem to find how to do this. Any suggestions would be welcome.
TIA
You can use factory to achieve that.
That's obviously not possible as is, however, I used something similar to this in a project to avoid having to add each new type to the container:
For your specific case, you could even make this shorter:
You could read configured type from the settings, load the required type via reflection and register it in service collection:
Such dynamic approach will not require any recompilation if you add or reconfigure new logger.