Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET Load assemblies at runtime Again

I posted a similar question a time ago. I need to load an assembly at runtime.

This is easy if I know the absolute path of the dll at runtime.

But I dont :( The assembly.Load() or LoadFromFile() fails if the file is not in the application root.

The only thing I have is the dll name. The dll could be located in the root, system32 or in even in the GAC.

Is it possible for .net to automatically determine where the dll is at, like for example : it should first look in the root. If its not there move on to the system folders, else try the GAC.

EDITED

I am using plug-in architecture. I do not need to register the dll. I have a multi user application. I have a applications table containing information regarding applications. Each application has a dll path associated with it, containing certain algorithms associated with that app. Hope this helps.

like image 541
MegaByte Avatar asked Jan 23 '23 21:01

MegaByte


2 Answers

I hope you've read up on the following. My suggestion...

  • How the runtime locates assemblies
  • You can give Assembly.LoadWithPartialName a whirl.. might work.. it says it will search the application folder and the GAC unlike Assembly.Load. (However its less safe.. coz you might end up with the wrong version of the DLL since you dont specify all 4 parts of the Assembly Name)
  • Also try AppDomainSetup.PrivateBinPath (AppDomain.AppendPrivatePath has been deprecated in favor of this) to add subfolders of the application root to the list of folders to probe assemblies for. You can also try copying over files from other places into a [AppFolder]\MySandboxForDLLsToLoad, which is added to the PrivateBinPath.
like image 177
Gishu Avatar answered Jan 26 '23 10:01

Gishu


When the current application looks for assemblies, it looks in several locations (bin folder, gac, etc..) if it can not find one, then the developer needs to manually tell the application where to look. You can do this by intercepting the AssemblyResolve event, and using the event args to tell the CLR where your assembly is.

AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;
....................
Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
   var strTempAssmbPath=
          Path.GetFullPath("C:\\Windows\\System32\\" + args.Name.Substring(0,  args.Name.IndexOf(",")) + ".dll");

   var strTempAssmbPath2=
          Path.GetFullPath("C:\\Windows\\" + args.Name.Substring(0,  args.Name.IndexOf(",")) + ".dll");


    if (File.Exists(strTempAssmbPath))
            return Assembly.LoadFrom(strTempAssmbPath);

    if (File.Exists(strTempAssmbPath2))
            return Assembly.LoadFrom(strTempAssmbPath2);
}
like image 34
Chris Kooken Avatar answered Jan 26 '23 10:01

Chris Kooken