Question

I was just wondering what happens if I was to load the same assembly bytes twice within a web app.

For example I have this code

byte[] assem = System.IO.File.ReadAllBytes(appRoot + "/Plugins/Plugin.dll");

var loadedAssem = Assembly.Load(assem);

var plugin = loadedAssem.CreateInstance("Plugin.ThePlugin") as IPlugin;

I ran this code and on the first request I assume it would load the assembly into ram ( or the http runtime appdomain? ) and then I can create instances of whatever is in there.

If I ran this code again, say on the second request what would happen to the assembly on the first request?

Would is still exist in ram? if so how does it differentiate between the two assemblies? or does it overwrite the previously declare classes?

This is for my understanding, as like I do in PHP its not just a case of "require_once".

Was it helpful?

Solution

This will load two distinct copies of the assembly, each of which can be used from your application. The types in each assembly are distinct types and will not inter-operate with one-another. For instance, if you take a Widget from Copy1 and try to pass it to a method that takes a Widget on Copy2, this will cause a runtime failure. It is not possible to unload assemblies once they have been loaded in this way (i.e. into your main AppDomain.)


Regarding instantiation:

  • If you use Assembly.CreateInstance (as shown in your post), this will create it from the Assembly instance you used to make the call.
  • If you use an Activator.CreateInstance that takes a string, you need to specify the assembly name. Since both loaded assemblies will have the same name in this case, it will use assembly resolution rules, which, I think by default, will favor the first match (so the assembly you loaded first.) I'm not certain of this. You can hook the AppDomain.AssemblyResolve event to provide your own prioritization and make it use your most-recently-loaded assembly.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top