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