从非Root目录加载程序集

问题描述 投票:1回答:1

我试图从根目录中的不同文件夹加载程序集到我的项目,并为它设置一个新的域。我的目标是在运行时加载和卸载。当ddl文件在应用程序的根目录下时,所有工作正常,但是一旦我把它放在文件夹插件中我得到错误文件找不到。我知道有很多这样的话题,但是它们不包括我的所有需求,而且它们中的任何一个都不是我所害怕的。它加载到当前域后工作..

示例代码:

  dllFileNames = Directory.GetFiles(path, "*.dll");

                ICollection<Assembly> assemblies = new List<Assembly>(dllFileNames.Length);

                AppDomain currentDomain = AppDomain.CurrentDomain;
                Evidence asEvidence = currentDomain.Evidence;
                AppDomainSetup aps = new AppDomainSetup
                {
                    ApplicationBase = @"[root of application]",
                    PrivateBinPath = @"[Plugin folder]"
                };

                AppDomain myDomain = AppDomain.CreateDomain("Plugins",asEvidence,aps);
                SimpleAssemblyLoader assemblyLoader = (SimpleAssemblyLoader)myDomain.CreateInstanceAndUnwrap(typeof(SimpleAssemblyLoader).Assembly.FullName, typeof(SimpleAssemblyLoader).FullName);

                foreach (string dllFile in dllFileNames)
                {

                         assemblyLoader.LoadFrom(dllFile);

                }

              var assemblyList =  myDomain.GetAssemblies(); // in here getting error :( file not found for no reason.

System.IO.FileNotFoundException:'无法加载文件或程序集'Name,Version = 1.0.0.0,Culture = neutral,PublicKeyToken = null'或其依赖项之一。该系统找不到指定的文件。'

public class SimpleAssemblyLoader : MarshalByRefObject
{
    public void Load(string path)
    {
        ValidatePath(path);

        Assembly.Load(path);
    }

    public void LoadFrom(string path)
    {
        ValidatePath(path);

        Assembly.LoadFrom(path);
    }

    private void ValidatePath(string path)
    {
        if (path == null)
        {
            throw new ArgumentNullException("path");
        }

        if (!System.IO.File.Exists(path))
        {
            throw new ArgumentException(string.Format("path \"{0}\" does not exist", path));
        }
    }
}
c# directory .net-assembly
1个回答
1
投票

AppDomain.BaseDirectory设置为您的插件文件夹。

或者注册AppDomain.AssemblyResolve事件以解决缺失的程序集。

对于.Net Core编程,请查看AssemblyLoadContext

© www.soinside.com 2019 - 2024. All rights reserved.