C# 依赖注入运行时(动态)注册 [英] C# Dependency Injection Runtime (dynamic) registration
问题描述
我使用的是 VS 2017 和 .NET Core.使用依赖注入,我想在运行时动态注册我的服务.我的目标是编写我的服务实例,在单独的程序集中实现服务接口.然后将服务名称/程序集名称添加到某种配置文件(或数据库表)中.
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屋!