Created
May 1, 2013 06:41
-
-
Save samuraisam/5494042 to your computer and use it in GitHub Desktop.
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; | |
| 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