Last active
July 19, 2016 13:24
-
-
Save jtheisen/fab9681f778232915428a2a97e445040 to your computer and use it in GitHub Desktop.
A ServiceLocator for Glimpse to improve startup time. *Doesn't work yet*!
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 Glimpse.Core.Framework; | |
using System; | |
using System.Collections.Generic; | |
using System.Diagnostics; | |
using System.Linq; | |
using System.Reflection; | |
namespace My | |
{ | |
public class TypeRepository | |
{ | |
public IEnumerable<Type> GetTypesForInterfaces(Type interf) | |
{ | |
List<Type> list = null; | |
if (interfaceToClassDict.TryGetValue(interf, out list)) | |
{ | |
return list; | |
} | |
return Enumerable.Empty<Type>(); | |
} | |
public TypeRepository(IEnumerable<Assembly> assemblies) | |
{ | |
foreach (var assembly in assemblies) | |
{ | |
var types = assembly.GetTypes(); | |
foreach (var type in types) | |
{ | |
if (!IsEligible(type)) continue; | |
var interfaces = type.GetInterfaces(); | |
foreach (var interf in interfaces) | |
{ | |
List<Type> list = null; | |
if (!interfaceToClassDict.TryGetValue(interf, out list)) | |
{ | |
interfaceToClassDict[interf] = list = new List<Type>(); | |
} | |
list.Add(type); | |
} | |
} | |
} | |
} | |
static Boolean IsEligible(Type type) | |
{ | |
if (!type.IsClass) return false; | |
if (type.IsAbstract) return false; | |
var constructor = type.GetConstructor(Type.EmptyTypes); | |
if (null == constructor) return false; | |
return true; | |
} | |
Dictionary<Type, List<Type>> interfaceToClassDict = new Dictionary<Type, List<Type>>(); | |
} | |
public class GlimpseServiceLocator : IServiceLocator | |
{ | |
public ICollection<T> GetAllInstances<T>() where T : class | |
{ | |
return ( | |
from t in repository.Value.GetTypesForInterfaces(typeof(T)) | |
select (T)Activator.CreateInstance(t) | |
).ToArray(); | |
} | |
public T GetInstance<T>() where T : class | |
{ | |
var type = repository.Value.GetTypesForInterfaces(typeof(T)).FirstOrDefault(); | |
if (type == null) | |
{ | |
Debug.WriteLine($"Could not satisfy request for type '{typeof(T).Name}'."); | |
return default(T); | |
} | |
return (T)Activator.CreateInstance(type); | |
} | |
static TypeRepository CreateRepository() | |
{ | |
var assemblies = AppDomain.CurrentDomain.GetAssemblies(); | |
var relevantAssemblies = assemblies.Where(a => a.FullName.StartsWith("Glimpse.")); | |
return new TypeRepository(relevantAssemblies); | |
} | |
static Lazy<TypeRepository> repository = new Lazy<TypeRepository>(CreateRepository); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment