我正在使用 VS 2017 和 .NET Core。
使用依赖注入,我想在运行时动态注册我的服务。我的目标是编写在单独的程序集中实现服务接口的服务实例。然后,服务名称/程序集名称将被添加到某种配置文件(或数据库表)中。
我的注册代码会做这样的事情:
var ServiceTypeName = LoadServiceAssembly(AssemblyName);
var serviceProvider = new ServiceCollection()
.AddTransient<IDILogger, "ConsoleDILogger">() // <--- Goal
.BuildServiceProvider();
var logger = serviceProvider.GetService(IDILogger);
显然,AddTransient 行将不起作用,因为这样的方法不存在。然而,它确实描述了这个想法。我想通过字符串名称注册类型,以便每次添加新服务类型时都不需要重新编译加载器应用程序。
我似乎找不到如何做到这一点。欢迎大家提出意见。
TIA
这显然是不可能的,但是,我在项目中使用了类似的东西,以避免必须将每个新类型添加到容器中:
var assembly = typeof(YourClass).Assembly; // I actually use Assembly.LoadFile with well-known names
var types = assembly.ExportedTypes
// filter types that are unrelated
.Where(x => x.IsClass && x.IsPublic);
foreach (var type in types)
{
// assume that we want to inject any class that implements an interface
// whose name is the type's name prefixed with I
services.AddScoped(type.GetInterface($"I{type.Name}"), type);
}
对于您的具体情况,您甚至可以缩短它:
var type = assembly.ExportedTypes.First(x => x.Name == runtimeName);
services.AddScoped(typeof(IDILogger), type);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)