Created
July 2, 2017 14:23
-
-
Save zirkelc/cf25c675e6c091dc159d662dc46b5538 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
public static class Instantiator | |
{ | |
static Dictionary<Type, Func<object>> compiledExpressions = new Dictionary<Type, Func<object>>(); | |
static Dictionary<Tuple<Type, Type>, Func<object>> genericCompiledExpressions = new Dictionary<Tuple<Type, Type>, Func<object>>(); | |
public static T CreateInstance<T>() | |
{ | |
return (T)CreateInstance(typeof(T)); | |
} | |
public static object CreateInstance(Type typeDefinition) | |
{ | |
Func<object> instance; | |
if (!compiledExpressions.TryGetValue(typeDefinition, out instance)) | |
{ | |
instance = Expression.Lambda<Func<object>>(Expression.New(typeDefinition)).Compile(); | |
compiledExpressions.Add(typeDefinition, instance); | |
} | |
return instance(); | |
} | |
public static object CreateGenericInstance(Type genericTypeDefinition, Type genericParameter) | |
{ | |
Func<object> instance; | |
var key = Tuple.Create(genericTypeDefinition, genericParameter); | |
if (!genericCompiledExpressions.TryGetValue(key, out instance)) | |
{ | |
var genericType = genericTypeDefinition.MakeGenericType(genericParameter); | |
instance = instance = Expression.Lambda<Func<object>>(Expression.New(genericType)).Compile(); | |
genericCompiledExpressions.Add(key, instance); | |
} | |
return instance(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment