Tuesday, March 12, 2013

Preloading assemblies from Application folder in C#

As you may know, AppDomain.CurrentDomain.GetAssemblies() returns list of assemblies that are loaded in current Application Domain. Even if your executing project has reference to some assembly there is no guarantee that this assembly has been already loaded. It will be loaded lazily on first use. But what if you need all assemblies now? For example, you want to search assemblies for classes that implement some interface or something else.

You can easily force loading assemblies into your Application Domain.

Let's create helper class to return list of all files in our Application folder(Bin folder in case of Web Application):
 public static class From  
 {  
   public static IEnumerable<FileInfo> AllFilesIn(string path, bool recursively = false)  
   {  
     return new DirectoryInfo(path)  
               .EnumerateFiles("*.*", recursively ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly);  
   }  
   public static IEnumerable<FileInfo> AllFilesInApplicationFolder()  
   {  
     var uri = new Uri(Assembly.GetExecutingAssembly().CodeBase);  
     return AllFilesIn(Path.GetDirectoryName(uri.LocalPath));  
   }  
 }  

So, now you can preload assemblies as follows:
 From.AllFilesInApplicationFolder().Where(f => f.Extension == ".dll").ForEach(fi => Assembly.LoadFrom(fi.FullName));  

This solution is applicable both for Desktop and Web Applications.

No comments:

Post a Comment