Pages

Monday, February 27, 2012

How to fix TypeLoadException was unhandled Error?

Problem: I got the following runtime error while debugging my application.
TypeLoadException was unhandled
















"Evaluate" is an interface method defined in a different project (Assembly A) and implemented in another project. (Assembly B).

Then I saw following warning message in the Error list:
Warning: Found conflicts between different versions of the same dependent assembly.

The given assembly name (Assembly C) for the above warmning is referenced by both Assembly A and Assembly B. It is a third party dll. Also, Assembly A is referenced by Assembly B.


Once I double clicked on the warning, it prompted me saying "One or more dependent assemblies have version conflicts. Do you want to fix these conflicts by adding binding redirect records in the app.config file?

Then, once I accepted that, the code chunk given below was automatically added to my App.config file.







Consequently, that has fixed the issue!

But I suspected that there can be some unused dlls as the above App.config entry is redirecting all assembly binding references for versions 0.0.0.0 to 3.1.3.42154 (the latest) to version 3.1.3.42154 dll. This should happen as you can't load multiple versions of the same assembly in the same app domain. So, without binding redirect, an attempt to load a different version of an already loaded assembly will fail.

Since the above code chunk sounds like a workaround to overcome the issue, I revisited the code to find the actual reason for the exception.

There, I could find that different versions of the same dll is used in two dependent projects.















So, when I refer the third party dll (Assembly C) from the same folder, same version, and remove the code chunk in the App.config, I did not get the "TypeLoadException" issue.

After doing some research on this I found that this may occur if you have an interface in one assembly and it's implementation in another, and the implementation assembly was build against a different version of the interface.

Also, this issue can occur if you load assembly dynamically using LoadFrom(string) method. I used LoadFrom method to invoke Assembly B.

Also, the project dependency given above is called as "diamond shaped" dependency which may cause this issue.

However, the error message is little bit mis-leading, but we can get some clue out of that. Exception can occur even the method is not executed during the runtime.

No comments:

Post a Comment