Last active
December 19, 2016 17:53
-
-
Save TheHunter/11217198 to your computer and use it in GitHub Desktop.
A generic class for loading assemblies dynamically a runtime using a Resolver delegate.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class AppStart | |
{ | |
private static HashSet<Assembly> Dependencies; | |
// In this method the assemblies will be loaded into internal collection. | |
public static void AppInitialize() | |
{ | |
Dependencies = new HashSet<Assembly>(); | |
LoadDependencyAssemblies(); | |
// This delegate serves for resolving missing assemblies not loaded by AppDomain, | |
// so through the delegate indicated into next instruction, the execution project can resolve dependecies assemlies | |
// not referenced directly into project. | |
AppDomain.CurrentDomain.AssemblyResolve += AssemblyResolver.Resolve; | |
} | |
private static void LoadDependencyAssemblies() | |
{ | |
//return the root path for the current execution project.. | |
string localPath = HostingEnvironment.MapPath("~"); | |
if (localPath == null) | |
return; | |
lock (Dependencies) | |
{ | |
string baseDir = Path.Combine(localPath, @"bin\Dependencies\"); | |
if (Directory.Exists(baseDir)) | |
{ | |
List<string> assNaming = new List<string>(Directory.GetFiles(baseDir, "*.dll", SearchOption.AllDirectories)); | |
if (assNaming.Count > 0) | |
{ | |
assNaming.All | |
( | |
s => | |
{ | |
try | |
{ | |
Dependencies.Add(Assembly.LoadFile(s)); | |
} | |
catch (Exception) | |
{ | |
} | |
return true; | |
} | |
); | |
} | |
} | |
} | |
} | |
// this is the class resolver... | |
public class AssemblyResolver | |
{ | |
public static Assembly Resolve(object sender, ResolveEventArgs args) | |
{ | |
// assembly to load couldn't be present into Dependecies, | |
// in this case null reference is returned. | |
Assembly dependency = Dependencies.FirstOrDefault(n => n.FullName == args.Name); | |
return dependency; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is an eample for resolving assemblies dependecies at runtime.