<PackageReference Include="System.ClientModel" Version="1.7.0" />

ReflectionModelBuilder

using System.ClientModel.Internal; using System.Collections.ObjectModel; using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; namespace System.ClientModel.Primitives { [System.Runtime.CompilerServices.NullableContext(1)] [System.Runtime.CompilerServices.Nullable(0)] internal class ReflectionModelBuilder : ModelReaderWriterTypeBuilder { private Type _type; protected override Type BuilderType => _type; public ReflectionModelBuilder(Type type) { _type = type; } [System.Diagnostics.CodeAnalysis.UnconditionalSuppressMessage("Trimming", "IL2077", Justification = "We will only call this when we went through ModelReaderWriter.Read which has DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors).")] protected override object CreateInstance() { return GetInstance(_type); } private static IPersistableModel<object> GetInstance([System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembers((System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes)7)] Type returnType) { if (returnType.IsArray) throw new InvalidOperationException(returnType.ToFriendlyName() + " does not implement IPersistableModel"); if (returnType.IsGenericType) { if (returnType.Namespace?.Equals("System.Collections.Immutable") ?? false) throw new InvalidOperationException(returnType.ToFriendlyName() + " does not implement IPersistableModel"); Type genericTypeDefinition = returnType.GetGenericTypeDefinition(); if (genericTypeDefinition.Equals(typeof(ReadOnlyCollection<>)) || genericTypeDefinition.Equals(typeof(ReadOnlyDictionary<, >))) throw new InvalidOperationException(returnType.ToFriendlyName() + " does not implement IPersistableModel"); } IPersistableModel<object> obj = GetObjectInstance(returnType) as IPersistableModel<object>; if (obj == null) throw new InvalidOperationException(returnType.ToFriendlyName() + " does not implement IPersistableModel"); return obj; } private static object GetObjectInstance([System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembers((System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes)7)] Type returnType) { PersistableModelProxyAttribute persistableModelProxyAttribute = Attribute.GetCustomAttribute(returnType, typeof(PersistableModelProxyAttribute), false) as PersistableModelProxyAttribute; Type type = (persistableModelProxyAttribute == null) ? returnType : persistableModelProxyAttribute.ProxyType; if (returnType.IsAbstract && persistableModelProxyAttribute == null) throw new InvalidOperationException(returnType.ToFriendlyName() + " must be decorated with PersistableModelProxyAttribute to be used with ModelReaderWriter"); object obj = Activator.CreateInstance(type, true); if (obj == null) throw new InvalidOperationException("Unable to create instance of " + type.ToFriendlyName() + "."); return obj; } } }