Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assembly.LoadFrom with path and full assembly name

Tags:

c#

.net

I am trying to implement dynamic loading of certain assemblies based on Environment.Is64BitProcess.
This basically works like this:

  • Register an event handler for the AppDomain.AssemblyResolve event
  • In the event handler load the assembly from the CPU type dependent sub path:

    private Assembly OnAssemblyResolve(object sender, ResolveEventArgs args)
    {
        // args.Name is the display name of an assembly, e.g.:
        // MyAssembly, Version=5.0.0.0, Culture=neutral, PublicKeyToken=abcdefghijklmn
        if(!args.Name.Contains("MyAssembly"))
            return null;
    
        var path = Path.Combine(GetCpuTypeDependentPath(), "MyAssembly.dll");
        return Assembly.LoadFrom(path);
    }
    

Now, this has the problem, that it doesn't check for the version, publicKeyToken etc of the loaded assembly.
What I would like to do now is to call Assembly.Load and simply supply an additional probing path. I know that this doesn't work as there is no such overload. Is there some other way to achieve my goal?

like image 383
Daniel Hilgarth Avatar asked Aug 07 '12 14:08

Daniel Hilgarth


Video Answer


2 Answers

Just compare the properties of the assembly you found with the one that was requested. For example, a version check could look like this:

private static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args) {
    var name = new AssemblyName(args.Name);
    string path = System.IO.Path.Combine(IntPtr.Size == 8 ? "x64" : "x86", name.Name + ".dll");
    path = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), path);
    var asm = Assembly.LoadFrom(path);
    var found = new AssemblyName(asm.FullName);
    if (name.Version != found.Version) throw new System.IO.FileNotFoundException(name.FullName);
    return asm;
}
like image 137
Hans Passant Avatar answered Nov 04 '22 23:11

Hans Passant


Short of probing assemblies yourself I don't see that you can do this. You'd only have to fire up another AppDomain that will search for matching assembly, so that you can unload assemblies loaded during probing. Unfortunately

like image 37
Nikola Radosavljević Avatar answered Nov 05 '22 01:11

Nikola Radosavljević