Skip to content

Instantly share code, notes, and snippets.

@TehWardy
Created February 12, 2019 18:34
Show Gist options
  • Save TehWardy/f3c476a139a7c9bb4ed63ed7f3015a21 to your computer and use it in GitHub Desktop.
Save TehWardy/f3c476a139a7c9bb4ed63ed7f3015a21 to your computer and use it in GitHub Desktop.
Reflection Based Assembly Loading
/// <summary>
/// Dynamically construct known t's from the assemblies available.
/// </summary>
public static T[] GetInstancesOf<T>()
{
var tType = typeof(T);
var types = GetStackAssemblies()
.SelectMany(a => a.GetTypes())
.Where(t => tType.IsAssignableFrom(t) && tType != t && t.IsClass && !t.IsAbstract)
.ToArray();
return types.Select(t => (T)Activator.CreateInstance(t)).ToArray();
}
/// <summary>
/// Gets the array of core stack assemblies to use for type searching.
/// </summary>
public static Assembly[] GetStackAssemblies()
{
if (stackAssemblies == null)
{
// some of the stack might not have been loaded, lets make sure we load everything so we can give a complete response
// first grab what's loaded
var loadedAlready = AppDomain.CurrentDomain
.GetAssemblies()
.Where(a => a.FullName.StartsWith("Core"))
.ToList();
// then grab the bin directory
var binDir = Assembly.GetExecutingAssembly().CodeBase
.Replace(Assembly.GetExecutingAssembly().CodeBase.Split('/').Last(), "")
.Replace("file:///", "")
.Replace("/", "\\");
// from the bin, grab our core dll files
var stackDlls = Directory.GetFiles(binDir)
.Select(i => i.ToLowerInvariant())
.Where(f => f.EndsWith("dll") && f.Split('\\').Last().StartsWith("MyCorp"))
.ToList();
// load the missing ones
foreach (var assemblyPath in stackDlls)
if (loadedAlready.All(a => a.CodeBase.ToLowerInvariant() != assemblyPath))
loadedAlready.Add(Assembly.LoadFile(assemblyPath));
// now everything is loaded, lets not do this again
stackAssemblies = loadedAlready.Distinct(new AssemblyComparer()).ToArray();
}
return stackAssemblies;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment