Wednesday, February 09, 2005

A question popped up. Let's say we have an application \Program Files\MyApp\MyApp.exe that references a class library \Program Files\MyApp\Framework\MyLib.dll. How can we avoid a TypeLoadException in this scenario?

To answer this let's take a look at how the type resolution works in CF. When an application code attempts to load type T, it first checks if the assembly that contains the type (the one referenced in the Type's full name) is already loaded in the current AppDomain. Obviously, if the appdomain already has the assembly, there is no reason to perform a costly file operation lookihng it up and loading it again. This suggests an easy way to “help” the loader to resolve a type. All you need to do is preload the assembly before the code attempts to use the type from that assembly. In our scenario the following code need to be made:

System.Reflection.Assembly.LoadFrom(@”\Program Files\MyApp\Framework\MyLib.dll”);

This will ensure that the types that belong to this class library are successfully resolved.

The next question is - when to load the assembly. The easy answer is - to play it safe, load all such assemblies in the Main, before the Application.Run. This approach has a disadvantage - a noticeable performance hit because a number of modules are being loaded in the memory before the UI started painting. Besides some of them might be never used. Because of this I would advise staggered load. The trick is to make sure the appropriate assembly is loaded before code execution has entered a block that defines/instantiates a variable of a type defined in that assembly. For example if you have a function:

void DoSomething()
{
MyType myVar = new MyType();
}

where MyType is defined in a dynamically-loaded assembly, and your code never ever call this function, there is no reason at all to load the assembly (provided the no type from that assembly is ever used outside that function).

By cleverly structuring your code you can avoid performance hit even if you have a large amount of dynamically loaded assemblies

2/9/2005 12:15:44 PM (Pacific Standard Time, UTC-08:00)  #    Comments [0]  |