【问题标题】:Replacement for AppDomain.GetLoadedAssemblies() in .NET Core?.NET Core 中 AppDomain.GetLoadedAssemblies() 的替换?
【发布时间】:2017-05-14 15:40:42
【问题描述】:

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

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

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

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

编辑:

我现在发现将Microsoft.Extensions.DependencyModel 添加到.netcoreapp1.1 项目是可行的。但是我实际上正在编写一个包含多个项目的解决方案,并且我需要在我的 .netstandard1.4 项目中进行这种类型加载,其中我的 DbContext 实现和实体类型配置是

【问题讨论】:

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


    【解决方案1】:

    here 广泛解释了您要查找的内容。作者建议创建一个 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 似乎不存在。
    • @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
    • 我实际上是在尝试在 .netcoreapp1.1 Web 应用程序引用的 .netstandard1.4 类库项目中实现这一点。这会有所作为吗?
    • @m.brookson 可悲的是,我不知道
    • 刚刚将Microsoft.Extensions.DependencyModel 添加到.netcoreapp1.1,它就在那里工作!不知何故需要在我的.netstandard1.4 项目中使用这些值。嗯……
    【解决方案2】:

    通过将我的 .netstandard 项目从 1.4 升级到 1.6 来解决此问题。 Microsoft.Extensions.DependencyModel 1.1.2 包现在可以使用了。

    编辑:

    使用.netstandard2.0 消除了对AppDomain polyfill 类的需求,因为它包含更多的.NET API,包括System.AppDomain

    【讨论】:

      猜你喜欢
      • 2021-10-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-23
      • 1970-01-01
      • 1970-01-01
      • 2018-12-22
      相关资源
      最近更新 更多