Add path to Current AppDomain

191 views Asked by At

I have two completely different directories. Directory 1 contains my application and Directory 2 having few assemblies. During run-time when application launches, I will load the assemblies. By default, the executing Assembly's AppDomain will discover the assemblies in Directory 1 (application folder) or GAC. If the file is not there, we will get the error. But I have to extend the AppDomain's search directory to search in Directory 2 also. That is, AppDomain will search Directory1 (local bin), then GAC, then other defaults at last search in Directory 2.

I have tried : 1. By setting PrivateBinPath, but it is restricted only within ApplicationBaseDirectory. 2. By AssemblyResolve, but it is not directly referenced. The AssemblyResolve code never hits also.

1

There are 1 answers

0
Abel On

Using the AssemblyResolve event is generally the correct way. If it is never hit, it is probably bound to too late. For instance, when the CLR encounters a method, it will compile it completely, resolving all its references. If such resolution fails, it will fail always. If you bind the AssemblyResolve event after any or all assemblies failed binding, the event will never hit.

To resolve this, make sure that the AssemblyResolve event is bound as early as possible. In an executable this is easy enough (first thing in the entry point of your application, or any cctor of a type you use there). In a library this can be harder, best practice approach is to use the module initializer, which is run whenever a module is loaded (most assemblies contain one module).

Since the module initializer cannot be set by C# or any other .NET language I know of, you have to resort to method weaving. I personally like Fody and as it turns out, there's a predefined Fody package called Fody Module Init for exactly this thing.

Just place, somewhere publicly in your library, the following code:

public static class ModuleInitializer
{
    public static void Initialize()
    {
        // bind to the CurrentDomain.AssemblyResolve event
    }
}

Fody also works with other languages (you don't specify which you use), but then you'll have to create the static ModuleInitializer class by hand.

Using this approach, you can be certain that the AssemblyResolve event will be called for any assembly that CLR's Fusion cannot find by itself.