Created
July 4, 2015 19:49
-
-
Save henkmollema/2e53f59d60833e2bea4f to your computer and use it in GitHub Desktop.
This file contains 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
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