Last active
December 16, 2015 09:48
-
-
Save dontjee/5415261 to your computer and use it in GitHub Desktop.
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
internal class ObjectConverterFactory | |
{ | |
private static readonly Dictionary<Type, IObjectToTypeConverter> _objectToTypeConverters = GetObjectToTypeConverters(); | |
public static IObjectToTypeConverter GetConverterFor( Type type ) | |
{ | |
Type typeToCheck = type; | |
while ( typeToCheck != typeof( object ) && typeToCheck != null ) | |
{ | |
if ( _objectToTypeConverters.ContainsKey( typeToCheck ) ) | |
{ | |
return _objectToTypeConverters[typeToCheck]; | |
} | |
typeToCheck = type.BaseType; | |
} | |
throw new NotSupportedException( string.Format( "The type {0} is not supported", type.Name ) ); | |
} | |
private static Dictionary<Type, IObjectToTypeConverter> GetObjectToTypeConverters() | |
{ | |
return Assembly.GetAssembly( typeof( ObjectConverterFactory ) ) | |
.GetTypes() | |
.Where( t => typeof( IObjectToTypeConverter ).IsAssignableFrom( t ) && !t.IsInterface && !t.IsAbstract ) | |
.SelectMany( t => | |
{ | |
var instance = Activator.CreateInstance( t ) as IObjectToTypeConverter; | |
return instance.GetConvertableTypes() | |
.Select( type => new KeyValuePair<Type, IObjectToTypeConverter>( type, instance ) ); | |
} ) | |
.ToDictionary( pair => pair.Key, pair => pair.Value ); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment