c# – 在.NET Core中替换AppDomain.GetLoadedAssemblies()?

前端之家收集整理的这篇文章主要介绍了c# – 在.NET Core中替换AppDomain.GetLoadedAssemblies()?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试编写一些逻辑来镜像原始.NET应用程序中的一些现有逻辑.在我的OnModelCreating()方法中,我想加载已加载程序集中的所有当前类型,以查找需要在模型中注册实体类型配置的类型.

这是在.NET中使用AppDomain.CurrentDomain.GetAssemblies()完成的.选择(a => a.GetTypes()),但.NET Core中不再存在AppDomain.

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

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

编辑:

我现在发现将Microsoft.Extensions.DependencyModel添加到.netcoreapp1.1项目可以正常工作.但是我实际上正在编写一个包含多个项目的解决方案,我在某种程度上需要在我的.netstandard1.4项目中执行此类型加载,其中我的DbContext实现和实体类型配置是

解决方法

您正在寻找的内容被广泛解释为 here.Autor建议创建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"));
    }
}
原文链接:https://www.f2er.com/netcore/243596.html

猜你在找的.NET Core相关文章