.NET Core中替代AppDomain.GetLoadedAssemblies()的方法是什么?

7

我试图编写一些逻辑来反映原始.NET应用程序中的某些逻辑。在我的OnModelCreating()方法中,我想加载所有当前已加载程序集中的类型,以查找需要在模型中进行实体类型配置的类型。

在.NET中,使用AppDomain.CurrentDomain.GetAssemblies().Select(a => a.GetTypes())来完成此操作,但是在.NET Core中,AppDomain不再存在。

有没有新的方法来做到这一点?

我在网上看到了一些示例,使用DependencyContext.Default.RuntimeLibraries,但是DependencyContext.Default似乎也不再存在。

编辑:

我现在发现将Microsoft.Extensions.DependencyModel添加到.netcoreapp1.1项目中可以解决问题。但是,我实际上正在编写一个具有多个项目的解决方案,我需要在我的.netstandard1.4项目中执行此类型加载。

2个回答

7
您要查找的内容在这里有广泛的解释:这里。作者建议创建一个polyfill。
如果该页面消失,我会将其复制粘贴。
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"));
    }
}

我在博客文章中看到过类似的内容,但是我已经添加了 Microsoft.Extensions.DependencyModel 包,但是 DependencyContext.Default 似乎不存在。 - mbrookson
@m.brookson 我刚刚创建了一个带有DependencyModel(版本1.1.2)的.NET Core 1.1应用程序,它完美地运行着。此外,可能(或不可能)相关的依赖项包括:Microsoft.DotNet.PlatformAbstractions 1.1.2, Microsoft.Extensions.DependencyModel 1.1.2, Newtonsoft.Json 9.0.1, System.Runtime.Serialization.Primitives 4.1.1 - MaLiN2223
我实际上正在尝试在一个.netstandard1.4类库项目中实现这个,该项目被一个.netcoreapp1.1 Web应用程序引用。那会有什么影响吗? - mbrookson
@m.brookson 很遗憾,我不知道。 - MaLiN2223
刚刚将 Microsoft.Extensions.DependencyModel 添加到 .netcoreapp1.1 中,它可以正常工作!不知道该如何在我的 .netstandard1.4 项目中使用这些值。嗯... - mbrookson
通过将我的.netstandard项目从1.4升级到1.6,解决了这个问题。现在可以使用Microsoft.Extensions.DependencyModel 1.1.2包。 - mbrookson

5
我通过将我的.netstandard项目从1.4升级到1.6来解决了这个问题。现在Microsoft.Extensions.DependencyModel 1.1.2包可以正常使用。 编辑: 使用.netstandard2.0可以避免需要一个AppDomain polyfill类的需求,因为它包含了许多更多的.NET API,包括System.AppDomain

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接