Skip to content

Instantly share code, notes, and snippets.

@deepumi
Last active August 1, 2018 20:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save deepumi/9ff477ba42323df69f886c369189040c to your computer and use it in GitHub Desktop.
Save deepumi/9ff477ba42323df69f886c369189040c to your computer and use it in GitHub Desktop.
Create instance using Reflection
public static class TypeActivator<T>
{
private delegate T Activator<T>(params object[] args);
private static readonly Dictionary<string, Activator<T>> _items = new Dictionary<string, Activator<T>>();
/// <summary>
///
/// </summary>
/// <returns></returns>
public static T Create()
{
lock (_items)
{
var type = typeof(T);
if (_items.TryGetValue(type.Name, out var res)) return res();
var lambda = Expression.Lambda(typeof(Activator<T>), Expression.New(type), Expression.Parameter(typeof(object[]), "args"));
var result = lambda.Compile() as Activator<T>;
_items.Add(type.Name, result);
return result();
}
}
}
public static class ActivatorCreateInstance
{
public static T Create<T>()
{
return Activator.CreateInstance<T>();
}
}
public static T CreateInstance<T>(Type objType) where T : class
{
Func<T> returnFunc;
if (!ActivatorStore<T>.Store.TryGetValue(objType.FullName, out returnFunc))
{
var dynMethod = new DynamicMethod(objType.Name, objType, null, objType);
ILGenerator ilGen = dynMethod.GetILGenerator();
ilGen.Emit(OpCodes.Newobj, objType.GetConstructor(Type.EmptyTypes));
ilGen.Emit(OpCodes.Ret);
returnFunc = dynMethod.CreateDelegate(typeof(Func<T>)) as Func<T>;
ActivatorStore<T>.Store[objType.FullName]= returnFunc;
}
return returnFunc();
}
internal static class ActivatorStore<T>
{
internal static IDictionary<string, Func<T>> Store = new ConcurrentDictionary<string, Func<T>>();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment