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

时间:2017-07-06 09:12:32

标签: c# asp.net inheritance asp.net-core

我正在使用不同的继承类我希望从同一个接口继承此类名

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>();
} 

2 个答案:

答案 0 :(得分:2)

您也可以像这样添加

foreach(var item in types)
{
    serviceCollection.AddTransient(typeof(ICollector), item);
} 

同样在寻找类型时,请尝试以下方法。

//get collectors
var types = typeof(CollectorA).Assembly
    .GetTypes()
    .Where(t => typeof(ICollector).IsAssignableFrom(t));

//add to service
foreach(var item in types)
{
    serviceCollection.AddTransient(typeof(ICollector), item);
} 

答案 1 :(得分:2)

  

.NET Core中没有AppDomain所以这个   AppDomain.CurrentDomain.GetAssemblies()也不存在(没有   .NET Standard 1.x有它。)这是GitHub issue详细说明   此

如果你想在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()或类型的替代方法。