Reputation: 1533
I am developing plugins for another application that is strong named, so any plugin that references it needs to be recompiled for each version.
So, I have a library (that doesn't reference the main application) that logs in to my website, and I've compiled it as a .dll
This is the code I use in each of the plugins to log in and check for updates:
var managerAssemblyPath = "Path to the .dll assembly";
var assembly = AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault(a => a.FullName.Equals("AssemblyName, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"));
if (assembly == null)
{
var assemblyBuffer = File.ReadAllBytes(managerAssemblyPath);
assembly = Assembly.Load(assemblyBuffer);
}
var t = assembly.GetType("Namespace.Class");
if (t == null)
{
var assemblyBuffer = File.ReadAllBytes(managerAssemblyPath);
assembly = Assembly.Load(assemblyBuffer);
t = assembly.GetType("Namespace.Class");
}
var methods = t.GetMethods();
var method = methods.Where(m => m.Name.Equals("CheckForUpdates")).ToArray()[1];
method.Invoke(null, new object[] { this.Id });
It does get the job done. The first plugin that's being loaded will have assembly == null in the first 'if'-condition and load the file. Then it'll get the type and call the CheckForUpdates method. When CheckForUpdates is called, the loaded class caches all the information needed for any of the other plugins in order to minimize traffic to the website (as a static class).
The next plugin finds the assembly by the FullName, but does not find the type. Because it doesn't find the type, it loads the assembly again. This is where the problem comes in. Because it loads the assembly again, it doesn't use the information that was cached by the first plugin, but rather logs in to the website again.
So with 5 plugins installed, it logs in to the website 5 times which is not really ideal.
I'd prefer to read the bytes from the dll and then load the bytes, because this way the file doesn't get locked, and typically I will run many instances of the application.
Can anyone help with how I can make sure the assembly only gets loaded once?
Upvotes: 2
Views: 247
Reputation: 878
.Net loads assemblies based on evidence which includes the assembly path. Loading an assembly from a byte stream bypasses that step of the verification process so .Net treats each loaded instance as a separate sand boxed instance, which causes lots of unpleasantness.
Upvotes: 0