using System; using System.Collections.Generic; using System.Reflection; using HeuristicLab.Persistence.Interfaces; namespace HeuristicLab.Persistence { public class Configuration { private readonly Dictionary formatters; private readonly List decomposers; private readonly Dictionary decomposerCache; public readonly IFormat Format; public Configuration(Dictionary formatters, IEnumerable decomposers) { this.formatters = new Dictionary(); foreach ( var pair in formatters ) { if (Format == null) { Format = pair.Value.Format; } else if (pair.Value.Format != Format ) { throw new ArgumentException("All formatters must have the same IFormat."); } this.formatters.Add(pair.Key, pair.Value); } this.decomposers = new List(decomposers); decomposerCache = new Dictionary(); } public IFormatter GetFormatter(Type type) { IFormatter formatter; formatters.TryGetValue(type, out formatter); return formatter; } public IDecomposer GetDecomposer(Type type) { IDecomposer decomposer; decomposerCache.TryGetValue(type, out decomposer); if (decomposer != null) return decomposer; foreach (IDecomposer d in decomposers) { if (d.CanDecompose(type)) { decomposerCache.Add(type, d); return d; } } return null; } } public class ConfigurationService { private static ConfigurationService instance; private readonly Dictionary> formatters; private readonly List decomposers; public Dictionary> AllFormatters { get { return formatters; } } public List AllDecomposers { get { return decomposers; } } public static ConfigurationService Instance { get { if (instance == null) { instance = new ConfigurationService(); } return instance; } } public ConfigurationService() { formatters = new Dictionary>(); decomposers = new List(); Reset(); } public void Reset() { Assembly defaultAssembly = Assembly.GetExecutingAssembly(); DiscoverFrom(defaultAssembly); foreach (Assembly a in AppDomain.CurrentDomain.GetAssemblies()) if ( a != defaultAssembly ) DiscoverFrom(a); } protected void DiscoverFrom(Assembly a) { foreach (Type t in a.GetTypes()) { if (t.GetInterface(typeof (IFormatter).FullName) != null) { try { IFormatter formatter = (IFormatter) Activator.CreateInstance(t, true); if ( ! formatters.ContainsKey(formatter.Format) ) { formatters.Add(formatter.Format, new List()); } formatters[formatter.Format].Add(formatter); } catch (MissingMethodException) { Console.WriteLine("WARNING: Could not instantiate {0}", t.FullName); } } if (t.GetInterface(typeof (IDecomposer).FullName) != null) { try { decomposers.Add((IDecomposer) Activator.CreateInstance(t, true)); } catch (MissingMethodException) { Console.WriteLine("WARNING: Could not instantiate {0}", t.FullName); } } } } public Configuration GetDefaultConfig(IFormat format) { Dictionary formatterConfig = new Dictionary(); foreach ( IFormatter f in formatters[format] ) { if ( ! formatterConfig.ContainsKey(f.Type) ) formatterConfig.Add(f.Type, f); } return new Configuration(formatterConfig, decomposers); } } }