如何使用dotnet core在运行时加载程序集

时间:2016-07-29 08:15:39

标签: c# .net .net-core

我有一个用于预加载程序集或启动新的可执行程序集的守护程序。

预加载程序集:

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 个答案:

答案 0 :(得分:3)

试着看看这篇文章:

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

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