开发者

How to load assemblies outside the appbase(more information)

开发者 https://www.devze.com 2023-03-20 17:51 出处:网络
I want to know how to load assemblies which are outside the Appbase and Appdomain. My problem is that I have a list of assemblies that are on a shared directory. My application needs to load these as

I want to know how to load assemblies which are outside the Appbase and Appdomain.

My problem is that I have a list of assemblies that are on a shared directory. My application needs to load these assemblies, which are located outside the path specified in the Appbase (path to the executable). I do not want to move them into the Appbase folder.

For more information, I have an application which is running in a distributed domain to test a collection of assemblies. When the application starts, it loads these assemblies from an arr开发者_运维技巧ay. When I test this application on my local desktop, it works well (loads and make reflection from assemblies, etc.), but from the cluster computers, it can't load those same assemblies, and throws the following Exception:

FileNotFoundException. Could not load file or assembly or one of its dependencies. The system cannot find the file specified.


There is an event that is fired if it can't find an assembly or one of its references:

AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);

Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
        {

        }

Add it before you're loading your assemblies. Put a breakpoint in it and in args there should be some info about the assembly you're missing


What About MSDN - Assembly Load File

string filePath = "C:\asmPath";
Assembly myAssembly = Assembly.LoadFile(filePath);

You can also define a probe path in your app.config (which I consider a better solution) and having the CLR loading the assemblies on demand. MSDN Probing Path

<configuration>
   <runtime>
      <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
         <probing privatePath="bin;bin2\subbin;bin3"/>
      </assemblyBinding>
   </runtime>
</configuration>


7 1/2 years late. You can't https://learn.microsoft.com/en-us/dotnet/framework/configure-apps/specify-assembly-location

The directories specified in privatePath must be subdirectories of the application base directory.


thanks to @hcb's instruction I finally solve this problem:

AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);

Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
    if (args.Name.Contains("Dll2Find"))
    {
        try
        {
            return Assembly.LoadFrom(@"D:\findHere\Dll2Find.dll");
        }
        catch (Exception)
        {
            return null;
        }
    }
    return null;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消