Click here to Skip to main content
15,881,248 members
Articles / Programming Languages / C#

AppDomain.AssemblyResolve Event Tips

Rate me:
Please Sign up or sign in to vote.
4.78/5 (7 votes)
5 Jan 2012CPOL2 min read 57.9K   12   7
AppDomain.AssemblyResolve event can be used to load referenced assemblies at runtime

AppDomain.AssemblyResolve event can be used to load referenced assemblies at runtime. This can be useful in multiple scenarios: you can use it to load a library from a different location or load a library based on bitness or load a library which is embedded in the executable file. In all cases, there are some tips and tricks which can help you to easily implement the event handler and avoid exceptions.

Tip 1: Use AssemblyName Class to Parse the Name of the Assembly

When the AssemblyResolve event is fired, you can use the Name property of ResolveEventArgs class to find the name of the requested assembly. However, it will also include version, culture and public key token of the assembly. Instead of manipulating the string to extract the name part, it is much more easier to construct a new instance of AssemblyName class and use the Name property which returns only the name of the library.

C#
private Assembly ResolveAssembly(object sender, ResolveEventArgs args)
{
    //args.Name looks like this:
    //MyLibrary, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
    //Don't parse it yourself
    string name = args.Name.Split(',')[0];

    //Use the AssemblyName class to get the name
    name = new AssemblyName(args.Name).Name;
}

Tip 2: AssemblyResolve Firing Multiple Times

AssemblyResolve event can fire multiple times for the same assembly. Instead of loading it again, you should return previously loaded assembly. To keep track of the assemblies you have loaded, you can use a dictionary or you can get the loaded assemblies by calling AppDomain.GetAssemblies method. Make sure that you use appropriate locking mechanism to prevent race conditions.

Tip 3: AssemblyResolve and FileNotFoundException

Even if you are loading the assembly in the AssemblyResolve event handler, you might still get a FileNotFoundException if you are not careful. For example, the following code will generate the exception (the main class is defined in the library we are loading):

C#
static void Main(string[] args)
{
    AppDomain.CurrentDomain.AssemblyResolve += ResolveAssembly;
    var mainClass = new MainClass();
    mainClass.Print();
}

static Assembly ResolveAssembly(object sender, ResolveEventArgs args)
{
    return Assembly.LoadFile(@"path to the library");
}

The exception is occurring because JIT tries to resolve all assemblies as soon as it hits the Main method. At that point, the AssemblyResolve event does not have any subscribers so the event is not raised at all. One way to solve the problem is to move the code which needs the assembly to a separate method:

C#
static void Main(string[] args)
{
    AppDomain.CurrentDomain.AssemblyResolve += ResolveAssembly;
}
static void Print()
{
    var mainClass = new MainClass();
    mainClass.Print();
}

static Assembly ResolveAssembly(object sender, ResolveEventArgs args)
{
    return Assembly.LoadFile(@"path to the library");
}

Another solution is to subscribe to the event before the Main method is hit. For example, you can change the Program class to a static class and put the assignment in static constructor.

C#
static class Program
{
    static Program()
    {
        AppDomain.CurrentDomain.AssemblyResolve += ResolveAssembly;
    }

    static void Main(string[] args)
    {
        var mainClass = new MainClass();
        mainClass.Print();
    }

    static Assembly ResolveAssembly(object sender, ResolveEventArgs args)
    {
        return Assembly.LoadFile(@"path to the library");
    }
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
Georgia Georgia
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
Questionsometimes it works sometimes it does not Pin
Mihai Pruna17-Jan-15 15:17
Mihai Pruna17-Jan-15 15:17 
QuestionWhat to do if you don't know anything about the assembly you've been asked to load? Pin
jcdege13-Oct-14 4:19
jcdege13-Oct-14 4:19 
GeneralMy vote of 5 Pin
Pragmateek28-Sep-13 7:16
professionalPragmateek28-Sep-13 7:16 
QuestionSaved my Day Pin
Alexander Rommel28-Jan-13 17:03
Alexander Rommel28-Jan-13 17:03 
After some hours of try & error (& headache) i found this post. For anyone having similar problem's please als take a look at the solution #4 here: AssemblyResolve event not hit[^]
Questionload assembly without AssemblyResolve Pin
Member 773855930-Jul-12 5:16
Member 773855930-Jul-12 5:16 
AnswerRe: load assembly without AssemblyResolve Pin
Logi Guna16-Feb-13 8:18
professionalLogi Guna16-Feb-13 8:18 
GeneralMy vote of 5 Pin
Wooters10-Jan-12 7:01
Wooters10-Jan-12 7:01 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.