Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assembly.Load and Assembly.LoadFrom differences?

My application loads assemblies it needs via the AppDomain.CurrentDomain.AssemblyResolve event. The assemblies are resources of the executing assembly.

private static Assembly OnResolveAssembly(object sender, ResolveEventArgs args)
{
    var executingAssembly = Assembly.GetExecutingAssembly();
    var assemblyName = new AssemblyName(args.Name);
    var resPath = assemblyName.Name + ".dll";

    using (var stream = executingAssembly.GetManifestResourceStream(resPath))
    {
        if (stream != null)
        {
            byte[] buffer = new byte[stream.Length];
            stream.Read(buffer, 0, buffer.Length);

            return Assembly.Load(buffer);
        }
    }

    return null;
}

In general this works fine but the assembly being loaded contains default styles for certain controls which won't get applied. BUT if I don't load the assembly via Assembly.Load but save it to a file and load it via Assembly.LoadFrom everything just works fine.

What's the difference between those? Why doesn't it work when loading the assembly directly from memory - or why DOES it work when first saving it to disk and then loading it with Assembly.LoadFrom?

I'm very confused and I want to load the assemblies directly from memory without saving them first.

like image 699
Cjreek Avatar asked Sep 28 '17 10:09

Cjreek


1 Answers

Assembly.Load and Assembly.LoadFrom uses different loading contexts. Assembly.Load loads assembly in the context of host assembly (default context). For correct loading all the dependant assemblies should be avaliable from host application path, GAC or should be loaded manually in advance.

Assembly.LoadFrom does't use host assembly context. It creates own loading context (load-from context) and able to automatically resolve dependant assemblies not present in the default context. These assemblies from a path that is not under the host application path.

It seems your default styles requires assemblies from a path that is not under the host application path.

like image 110
Igor Buchelnikov Avatar answered Oct 31 '22 18:10

Igor Buchelnikov