AutoMapper Factory Methods and Claims

Viewed 155

The Question: How do I get a value from HttpContext.User.Claims into a ConstructUsing call? Or more broadly, how do I construct something via a factory method when I have a dependency on HttpContext.User.Claims?


I'm trying to set up an AutoMapper mapping against a factory method. This has lead me to ConstructUsing():

CreateMap<SourceType, DestinationType>()
             .ConstructUsing((src, context) => DestinationType.Factory.Create(
                 src.SomeProperty,
                 "RUT-OH!", // This value comes from HttpContext.User.Claims
                 ...
             ));

However, the second property comes from HttpContext.User.Claims

I've created a value resolver to pull this out of the context:

public class SecretIdResolver : IValueResolver<SourceType, DestinationType, string>
{
    private IHttpContextAccessor _httpContextAccessor;

    public SecretIdResolver(IHttpContextAccessor httpContextAccessor)
    {
        _httpContextAccessor = httpContextAccessor;
    }

    public string Resolve(SourceType source, DestinationType destination, string destMember, ResolutionContext context)
    {
        return _httpContextAccessor.HttpContext.User.Claims.First(c => c.Type == "SecretId").Value;
    }
}

But there doesn't seem to be any way to leverage the Value Resolver when using ConstructUsing.

1 Answers
Related