public static ICompiledSerializer Wrap(IProtoTypeSerializer head, RuntimeTypeModel model) { if (!(head is ICompiledSerializer result)) { ConstructorInfo ctor; try { if (head.IsSubType) { ctor = Helpers.GetConstructor(typeof(InheritanceCompiledSerializer <,>).MakeGenericType(head.BaseType, head.ExpectedType), new Type[] { typeof(IProtoTypeSerializer), typeof(RuntimeTypeModel) }, true); } else { ctor = Helpers.GetConstructor(typeof(SimpleCompiledSerializer <>).MakeGenericType(head.BaseType), new Type[] { typeof(IProtoTypeSerializer), typeof(RuntimeTypeModel) }, true); } } catch (Exception ex) { throw new InvalidOperationException($"Unable to wrap {head.BaseType.NormalizeName()}/{head.ExpectedType.NormalizeName()}", ex); } try { result = (CompiledSerializer)ctor.Invoke(new object[] { head, model }); } catch (System.Reflection.TargetInvocationException tie) { throw new InvalidOperationException($"Unable to wrap {head.BaseType.NormalizeName()}/{head.ExpectedType.NormalizeName()}: {tie.InnerException.Message} ({head.GetType().NormalizeName()})", tie.InnerException); } Debug.Assert(result.ExpectedType == head.ExpectedType); } return(result); }