gpt4 book ai didi

c# - Asp.Net Core v1.1 从同一解决方案中的另一个项目获取继承的类名

转载 作者:太空宇宙 更新时间:2023-11-03 21:01:40 24 4
gpt4 key购买 nike

我正在使用不同的继承类,我希望从同一接口(interface)继承此类名称

public class CollectorA : ICollector
{
public string CollectSomething()
{
//DO Something
}
}
public class CollectorB : ICollector
{
public string CollectSomething()
{
//DO Something
}
}

我想这样做:

public void Init(IServiceCollection serviceCollection)
{

var types = AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(assembly => assembly.GetTypes())
.Where(type => type.IsInstanceOfType(typeof(ICollector)));

获取类型返回 null 我尝试了 AppContext 但仍然无效。

foreach(var item in types)
{
serviceCollection.AddTransient<ICollector,item.Name>();
}

最佳答案

There is no AppDomain in .NET Core so this AppDomain.CurrentDomain.GetAssemblies() is not there as well(None of .NET Standard 1.x has it.) Here's the GitHub issue detailing this.

如果您想在 blog 中使用 PolyFill (AppDomain) 的方法,这是代码

public class AppDomain
{
public static AppDomain CurrentDomain { get; private set; }

static AppDomain()
{
CurrentDomain = new AppDomain();
}

public Assembly[] GetAssemblies()
{
var assemblies = new List<Assembly>();
var dependencies = DependencyContext.Default.RuntimeLibraries;
foreach (var library in dependencies)
{
if (IsCandidateCompilationLibrary(library))
{
var assembly = Assembly.Load(new AssemblyName(library.Name));
assemblies.Add(assembly);
}
}
return assemblies.ToArray();
}

private static bool IsCandidateCompilationLibrary(RuntimeLibrary compilationLibrary)
{
return compilationLibrary.Name == ("Specify")
|| compilationLibrary.Dependencies.Any(d => d.Name.StartsWith("Specify"));
}
}

然后你可以这样使用

var types = AppDomain.CurrentDomain.GetAssemblies().SelectMany(ass => ass.ExportedTypes)
.Where(type => type.IsInstanceOfType(typeof(ICollector)));
foreach (var item in types)
{
services.AddTransient(typeof(ICollector), item);
}

有关替代方法,请参阅此 SO post获取 GetAssemblies() 或 Types 的替代方法。

关于c# - Asp.Net Core v1.1 从同一解决方案中的另一个项目获取继承的类名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44944575/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com