C#依赖注入运行时(动态)注册 [英] C# Dependency Injection Runtime (dynamic) registration
问题描述
我正在使用VS 2017和.NET Core。
使用依赖注入,我想在运行时动态注册我的服务。我的目标是编写服务实例,以在单独的程序集中实现服务接口。然后,服务名称/程序集名称将添加到某种配置文件(或db表)中。
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);
很显然,AddTransient行将不起作用,因为这种方法不存在。但是,它确实描述了这个想法。我想通过字符串名称注册该类型,以便不需要在每次添加新服务类型时都重新编译加载器应用程序。
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 could read configured type from the settings, load the required type via reflection and register it in service collection:
// Read from config
var assemblyPath = "...";
var typeName = "...";
var assembly = Assembly.LoadFrom(assemblyPath);
var loggerType = assembly.GetType(typeName);
var serviceProvider = new ServiceCollection()
.AddTransient(typeof(IDILogger), loggerType)
.BuildServiceProvider();
var logger = serviceProvider.GetService<IDILogger>();
如果添加或重新配置新的记录器,则这种动态方法不需要任何重新编译。
Such dynamic approach will not require any recompilation if you add or reconfigure new logger.
这篇关于C#依赖注入运行时(动态)注册的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!