Skip to content

Instantly share code, notes, and snippets.

@henkmollema
Created July 4, 2015 19:49
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save henkmollema/2e53f59d60833e2bea4f to your computer and use it in GitHub Desktop.
Save henkmollema/2e53f59d60833e2bea4f to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Microsoft.Framework.Runtime;
namespace SomeApp
{
public class TypeFinder
{
private static readonly Assembly _coreAssembly = typeof(TypeFinder).GetTypeInfo().Assembly;
private static readonly AssemblyName _coreAssemblyName = new AssemblyName(_coreAssembly.FullName);
private readonly ILibraryManager _libraryManager;
public TypeFinder(ILibraryManager libraryManager)
{
_libraryManager = libraryManager;
}
public Type FindType(string name, bool throwIfNotFound = false)
{
foreach (var assembly in GetLoadedAssemblies())
{
foreach (var candiate in assembly.ExportedTypes)
{
if (string.Equals(name, candiate.FullName))
{
return candiate;
}
}
}
if (!throwIfNotFound)
{
return null;
}
throw new InvalidOperationException($"Cannot find a type with the name '{name}'.");
}
public IEnumerable<Assembly> GetLoadedAssemblies()
{
return _libraryManager.GetReferencingLibraries(_coreAssemblyName.Name)
.Select(info => Assembly.Load(new AssemblyName(info.Name)));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment