Skip to content

Instantly share code, notes, and snippets.

@samuraisam
Created May 1, 2013 06:41
Show Gist options
  • Select an option

  • Save samuraisam/5494042 to your computer and use it in GitHub Desktop.

Select an option

Save samuraisam/5494042 to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
namespace Utils
{
public class UnknownTypeException : Exception
{
}
public class TypeRegistry
{
private static Dictionary<string, Type> reverseLookupTable = new Dictionary<string, Type>(); // first level cache (caches GetInstance<T>(string))
private static Dictionary<string, List<Type>> implementationCache = new Dictionary<string, List<Type>>(); // second level cache (caches GetAllImplementationsOfInterface(Type))
public static List<Type> GetAllImplementationsOfInterface<T>()
{
Type interfaceType = typeof(T);
var typeName = interfaceType.ToString();
if (implementationCache.ContainsKey(typeName)) {
return implementationCache[typeName];
}
var result = new List<Type>();
System.Reflection.Assembly[] allAssemblies = AppDomain.CurrentDomain.GetAssemblies();
foreach (var assembly in allAssemblies) {
Type[] types = assembly.GetTypes();
foreach (var inspectedType in types) {
var interfaces = inspectedType.FindInterfaces((Type typeObj, Object criteriaObj) => {
if (typeObj.ToString().Equals(typeName)) { // Type.IsEquivalentTo(Type) is unavailable in MonoTouch
return true;
}
return false;
}, null);
if (interfaces.Length > 0) {
result.Add(inspectedType);
}
}
}
implementationCache[typeName] = result;
return result;
}
public static T GetInstance<T>(string implementationName)
{
Type desiredType = null;
if (reverseLookupTable.ContainsKey(implementationName)) {
desiredType = reverseLookupTable[implementationName];
} else {
List<Type> allImplementations = GetAllImplementationsOfInterface<T>();
foreach (Type inspectedType in allImplementations) {
if (inspectedType.ToString().Equals(implementationName)) {
desiredType = inspectedType;
reverseLookupTable[implementationName] = desiredType;
}
}
}
if (desiredType == null) {
throw new UnknownTypeException();
}
T ret = (T)Activator.CreateInstance(desiredType);
return ret;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment