2016-07-29 112 views
2

我有一个deamon用于预加载程序集或启动新的可执行程序集。如何使用dotnet核心在运行时加载程序集

将其预加载组件:

Assembly assembly = Assembly.LoadFile(dllPath); 

要启动DLL:

AppDomain.CurrentDomain.ExecuteAssembly(executablePath, args); 

,但我无法找到netcoreapp1.0 API的LoadFile或AppDomain中的类。

如何将其移植到dotnet核心?


我试图使用LoadFromAssemblyPath和AssemblyLoadContext。 但它会在运行时发生异常。

这里是代码:

using System; 
using System.Runtime.Loader; 
using System.Reflection; 
using System.IO; 

namespace Tizen.DotnetLauncher 
{ 
    class Shield 
    { 
    public static void Main(string[] args) 
    { 

     if (args.Length < 1) return; 

     var asl = new AssemblyLoader(); 
     string fpath = Path.GetFullPath(args[0]); 
     Console.WriteLine(fpath); 
     var asm = asl.LoadFromAssemblyPath(fpath); 

     Type[] types = null; 

     try 
     { 
      types = asm.GetTypes(); 
     } 
     catch (ReflectionTypeLoadException e) 
     { 
      foreach (Exception ex in e.LoaderExceptions) 
      { 
       Console.WriteLine(ex); 
      } 
     } 

     foreach (Type info in types) 
     { 
      Console.WriteLine(info.GetTypeInfo()); 
     } 
    } 

    class AssemblyLoader : AssemblyLoadContext 
    { 
     protected override Assembly Load(AssemblyName assemblyName) 
     { 
      return null; 
     } 
    } 
    } 
} 

LoaderExceptions输出:

System.IO.FileNotFoundException: Could not load file or assembly 'System.Runtime, Version=4.1.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'. The system cannot find the file specified. 

File name: 'System.Runtime, Version=4.1.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' ---> System.IO.FileNotFoundException: Could not load the specified file. 
File name: 'System.Runtime' 
    at System.Runtime.Loader.AssemblyLoadContext.ResolveUsingEvent(AssemblyName assemblyName) 
    at System.Runtime.Loader.AssemblyLoadContext.ResolveUsingResolvingEvent(IntPtr gchManagedAssemblyLoadContext, AssemblyName assemblyName) 

例外

+1

可能的重复[如何加载位于.net核心控制台应用程序中的文件夹中的程序集](http://stackoverflow.com/questions/37895278/how-to-load-assemblies-located-in-a-folder -in-net-core-console-app) – Mat

回答

1

尝试看看这个帖子:

How to load assemblies located in a folder in .net core console app

在.NET核心中,AppDomain的概念不再存在。

+1

我在链接中找不到DependencyContext类。当我从LoadFromAssemblyPath()中用Assembly对象调用GetTypes()时,我得到很多异常,例如“System.IO.FileNotFoundException:无法加载文件或程序集”System.Runtime,Version = 4.1.1.0,Culture = neutral,PublicKeyToken = b03f5f7f11d50a3a'。系统找不到指定的文件。“ –

+0

@piuslee它位于Microsoft.Extensions.DependencyModel nuget lib中。也就是说,你可以从System.AppDomain nuget包获取AppDomain – Sinaesthetic

相关问题