Wednesday, 15 May 2013

Loading assemblies using Assembly.Load , Assembly.LoadFrom and Assembly.LoadFile


While working in .Net I came across various scenarios in which I had to manually load assemblies into my application. This gave me opportunity to learn about two well known method of Assembly Loading Assembly.Load(), Assembly.LoadFrom() and one less known method Assembly.LoadFile().

Ok ..let me start by asking some questions

1. Can I load multiple versions of same assembly in a particular AppDomain ?
2. Can I have two copies of same assembly if yes which loaded assembly will have priority ?
3. The last one ....Can I have n copies of an identical assembly loaded in an application domain.? how will system behave in that case?

I hope some of you may find these questions silly and some may be thinking that how does that matter.

let me first explain what all Assembly.Load****() method does before I start answering the questions

Assembly.Load():
Assembly.load takes the fully qualified assembly name and uses the .Net defined algorithm to search for an assembly. you can find the more detail here regarding  How Runtime Locates Assemblies. Using this method you can load assembly of a single version only once.

Assembly.LoadFrom()
Assembly.LoadFrom takes the full path of the assembly and if you call this method it will load assembly into the application domain provided it has not been loaded from same path by this or any of  other method.The beauty of this is that  it does not load same assembly again from any other path if it has been loaded by this method before.
for example lets say i have MyAssembly.dll at following path

  1. Application output path say C:\MyApplication\bin\Debug
  2. At path C:\MyApplication\ExternalAssemblies
  3. AT path C:\TestAssemblyLoading
When the application will run this assembly will automatically be loaded from first path. Now if I try to load the assembly using Assembly.LoadFrom from path 1 it will not be loaded. but if i do so using path 2 the assembly will be loaded again. but after that if i try to load assembly from path 3 using Assembly.LoadFrom it will not be loaded now as it has already been loaded from path 2. 

In short Assembly.LoadFrom allows assembly to be loaded once from  a path from which it not been loaded yet.


So using above two methods you can load an assembly at least for two times even if everything in those assemblies is same.

Assembly.LoadFile()
This is the most lazy method you can say. It try to minimise its work and does not look for anything. If you call this method if will load the assembly every time in the AppDomain. No no don't think it that lazy if you give this method same location again it will not load the assembly again from same path but it will do if path is different. So to get an assembly loaded 10 times you need to have 10 different location where the same assembly is present.

As a thumb rule you should always rely on Assembly.Load in case you know the path of assembly is not in .Net search path use Assembly.LoadFrom() but even in that case check using AppDomain.GetAssemblies() method if the assembly is already loaded before into the AppDomain.

For long time I was confused why .Net is providing a silly method like Assembly.LoadFile() but later i came to know that their may be scenario in which the architecture of product may be such that it is loading assembly dynamically from the various locations based on the requirement but the versions are same in all folder.

For example lets say i am making an international product which have resources in an assembly which is present in the folder named after the country.For simplicity purpose i want to keep the version and assembly name same for all these assemblies.  Now the server is  present in one country and the request are coming from all over the world. The server part need to load all the assemblies with same version and name based on from which country the request is coming.  Application is retrieving resource text using reflection by loading the assembly Now to achieve this we have to use Assembly.LoadFile so that we can load all the assemblies in spite of their version and name is same.

Now i hope you must be have got the answers of all the questions i asked at start of this topic. Still some thing i want to tell you may be left ...Lets see

Ans 1. This is obviously yes, any of the above method will do that.
Ans 2. The answer is yes but the explanation of other part is tricky.

look at the below code
I have an assembly TestAssembly.dll which i have in two folders f1 and f2. I am trying to load assemblies dynamically taking advantage of Assembly.LoadFile method.



Now look at the last  line. This line will fail with the error.
[A]TestAssembly.TestClass cannot be cast to [B]TestAssembly.TestClass. Type A originates from 'TestAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' in the context 'LoadNeither' at location 'C:\Samples\AssemblyLoading\MultipleAssemblyLoading\f2\TestAssembly.dll'. Type B originates from 'TestAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' in the context 'Default' at location 'C:\Samples\AssemblyLoading\MultipleAssemblyLoading\MultipleAssemblyLoading\bin\Debug\TestAssembly.dll'.

To find the reason for this let look at the variable loadedAssemblies in QuickWatch window. See the result below.

The assembly TestAssembly has been loaded three times.Once because the project has a reference to it and other two we loaded by our code. Now when we try to cast "obj" into TestClass which is a type of this assembly the compiler will throw an error because the type belongs to assembly loaded in loop and we are trying to cast it into the type which is coming from the assembly referenced into the project directly . We know they are same but the compiler doesn't (a common mistake isn't it ).

We need to take a precaution while using this type of code when multiple assembly of same version has been loaded. In a small code I wrote it is very easy to find the problem but in a bigger system its can be cumbersome.
Ans 3. Obviously now you know the answer is yes and the behaviour of the system will be same as i explained above.

No comments:

Post a Comment