MetadataWrapper
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.CompilerServices;
namespace Stashbox.Resolution.Wrappers
{
internal class MetadataWrapper : IServiceWrapper, IResolver
{
[System.Runtime.CompilerServices.Nullable(1)]
private static readonly HashSet<Type> SupportedTypes = new HashSet<Type> {
typeof(ValueTuple<, >),
typeof(Tuple<, >),
typeof(Metadata<, >)
};
[System.Runtime.CompilerServices.NullableContext(1)]
private static bool IsMetadataType(Type type)
{
if (type.IsClosedGenericType())
return SupportedTypes.Contains(type.GetGenericTypeDefinition());
return false;
}
[System.Runtime.CompilerServices.NullableContext(1)]
public Expression WrapExpression(TypeInformation originalTypeInformation, TypeInformation wrappedTypeInformation, ServiceContext serviceContext)
{
Type[] genericArguments = originalTypeInformation.Type.GetGenericArguments();
ConstructorInfo constructor = originalTypeInformation.Type.GetConstructor(genericArguments);
object obj = serviceContext.ServiceRegistration?.Metadata;
return constructor.MakeNew(serviceContext.ServiceExpression, obj.AsConstant());
}
public bool TryUnWrap(TypeInformation typeInformation, out TypeInformation unWrappedType)
{
if (!IsMetadataType(typeInformation.Type)) {
unWrappedType = default(TypeInformation);
return false;
}
Type[] genericArguments = typeInformation.Type.GetGenericArguments();
Type type = genericArguments[0];
Type metadataType = genericArguments[1];
unWrappedType = typeInformation.Clone(type, null, metadataType);
return true;
}
}
}