internal static dynamic CreateTypeInstance(string typeName, object instance) { Type type; if (!_typeCache.TryGetValue(typeName, out type)) throw new NotSupportedException("Unknown Horizon Wrapper type."); // Now we have our type. Let's create an instance from it: var actualType = instance.GetType(); dynamic result; if (actualType.IsPublic) { result = Info.Create(type, instance); } else { Delegate @delegate; if (!_internalWrapperCache.TryGetValue(typeName, out @delegate)) { var method = new DynamicMethod("Create_" + typeName, type, new[] { actualType }, type.Module, skipVisibility: true); var generator = method.GetILGenerator(); generator.Emit(OpCodes.Ldarg_0); generator.Emit(OpCodes.Newobj, type.GetConstructors().First()); generator.Emit(OpCodes.Ret); _internalWrapperCache[typeName] = @delegate = method.Build(); } result = @delegate.DynamicInvoke(instance); } return result; }