Skip to content

Instantly share code, notes, and snippets.

@hiiru
Last active April 24, 2019 07:00
Show Gist options
  • Save hiiru/f106fd974564b8d74f9ed3253d3ec632 to your computer and use it in GitHub Desktop.
Save hiiru/f106fd974564b8d74f9ed3253d3ec632 to your computer and use it in GitHub Desktop.
Reflection type lookup and constructor lookup with cache
private static readonly ConcurrentDictionary<string, Type> _typeCache = new ConcurrentDictionary<string, Type>();
public static Type GetTypeByFullName(string fullName)
{
if (_typeCache.TryGetValue(fullName, out Type type))
return type;
var paramTypes = GetAllTypesOf(typeof(Param));
if (paramTypes.Any())
{
var match = paramTypes.FirstOrDefault(x => x.FullName == fullName);
if (match != null)
{
type = match;
}
}
_typeCache[fullName] = type;
return type;
}
private static IEnumerable<Type> GetAllTypesOf(Type baseType)
{
var platform = Environment.OSVersion.Platform.ToString();
var runtimeAssemblyNames = DependencyContext.Default.GetRuntimeAssemblyNames(platform);
return runtimeAssemblyNames
.Select(Assembly.Load)
.SelectMany(a => a.ExportedTypes)
.Where(t => baseType.IsAssignableFrom(t));
}
private static readonly ConcurrentDictionary<Type, Func<object>> _ctxLookup = new ConcurrentDictionary<Type, Func<object>>();
public static object CreateObject(Type type)
{
var ctx = _ctxLookup.GetOrAdd(type, x => Expression.Lambda<Func<object>>(Expression.New(type)).Compile());
if (ctx == null)
return null;
return ctx();
}
namespace ExampleModels {
public abstract class Param
{
}
public class TextParam : Param
{
public string Text { get; set; }
}
public class IntParam : Param
{
public int Number { get; set; }
}
}
var fullName="ExampleModels.IntParam";
var type=GetTypeByFullName(fullName);
var instance=CreateObject(type);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment