Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looking for .NET Assembly in a different place [duplicate]

How can I tell my .NET application where to look for a particular assembly which it needs (other than the GAC or the folder where the application runs from)? For example I would like to put an assembly in the user's Temp folder and have my application know that the referenced Assembly is in the temp folder.

Thanks

like image 345
G-Man Avatar asked Oct 13 '09 17:10

G-Man


1 Answers

you can use the AppDomain.AssemblyResolve event to add custom Assembly Resolvers. This allows you to point at other directories or even databases to get assemblies as needed.

I have even used similar code to download assemblies from a database and store in IsolatedStorage. The file name as a hash of the full Assembly name. Then the database would only need to download on the first time you resolve and all future resolutions will be served by the file system. The best about about the AssemblyResolve event is you can use it Type.GetType() and the built in Serializers.

static string lookupPath = @"c:\otherbin";

static void Main(string[] args)
{
    AppDomain.CurrentDomain.AssemblyResolve += 
        new ResolveEventHandler(CurrentDomain_AssemblyResolve);
}

static Assembly CurrentDomain_AssemblyResolve(object sender, 
                                              ResolveEventArgs args)
{
    var assemblyname = new AssemblyName(args.Name).Name;
    var assemblyFileName = Path.Combine(lookupPath, assemblyname + ".dll");
    var assembly = Assembly.LoadFrom(assemblyFileName);
    return assembly;
}
like image 97
Matthew Whited Avatar answered Sep 20 '22 19:09

Matthew Whited