Created
January 28, 2015 11:07
-
-
Save jrgcubano/76cb759b29232784ffe8 to your computer and use it in GitHub Desktop.
Type discovery in Assemblies using Attributes
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
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Text; | |
using System.Reflection; | |
namespace AssemblyDiscoveryConsole | |
{ | |
// The attribute class you are looking for within external assemblies | |
public class SomeAttribute : Attribute | |
{ | |
} | |
public class TypeFinder | |
{ | |
public string[] LoadTypes(string assemblyFilename) | |
{ | |
AppDomain appDomain = AppDomain.CreateDomain("TypeFinder"); | |
try | |
{ | |
// Load and query asseblies in domain and return results | |
AssemblyReflector ar = (AssemblyReflector)appDomain.CreateInstanceAndUnwrap( | |
typeof(AssemblyReflector).Assembly.FullName, | |
typeof(AssemblyReflector).FullName); | |
return ar.LoadTypes(assemblyFilename); | |
} | |
finally | |
{ | |
// unload the temporary domain | |
AppDomain.Unload(appDomain); | |
} | |
} | |
/// <summary> | |
/// Class used to load and query assemblies within "TypeFinder" Domain | |
/// </summary> | |
private class AssemblyReflector : MarshalByRefObject | |
{ | |
private IEnumerable<string> EnumerateTypes(string assemblyFilename) | |
{ | |
Assembly asm = Assembly.LoadFile(assemblyFilename); | |
if (asm == null) throw new Exception("Assembly not found"); | |
foreach (Type t in asm.GetTypes()) | |
{ | |
if (t.GetCustomAttributes(typeof(SomeAttribute), true).FirstOrDefault() != null) | |
{ | |
yield return t.AssemblyQualifiedName; | |
} | |
} | |
} | |
public string[] LoadTypes(string assemblyFilename) | |
{ | |
return EnumerateTypes(assemblyFilename).ToArray(); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment