C#: Load a COM dll at runtime?


7down voteaccepted When the .NET assembly resolver is unable to find a referenced assembly at runtime (in this case, it cannot find the particular wrapper DLL version the application was linked against), its default behavior is to fail and essentially crash the application. However, this behavior can be overridden by hooking the AppDomain.AssemblyResolve event. This event is fired whenever a referenced assembly cannot be found, and it gives you the opportunity to substitute another assembly in place of the missing one (provided that they are compatible). So, for instance, you could substitute an older version of the wrapper DLL that you load yourself.

The best way I’ve found to do this is to add a static constructor on the main class of the application that hooks the event, e.g.:

using System.Reflection;

static Program()


AppDomain.CurrentDomain.AssemblyResolve += delegate(object sender, ResolveEventArgs e)


AssemblyName requestedName = new AssemblyName(e.Name);

if (requestedName.Name == "Office11Wrapper")


// Put code here to load whatever version of the assembly you actually have

return Assembly.LoadFile("Office11Wrapper.DLL");




return null;




By putting this in a static constructor of the main application class, it is guaranteed to run before any code attempts to access anything in the wrapper DLL, ensuring that the hook is in place ahead of time.

You can also use policy files to do version redirection, but that tends to be more complex.

Other references



Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s