Read Claims from Automapper Value Resolver on NET

2019-08-21 15:19发布

问题:

I have a Automapper Mapping Profile like this:

CreateMap<MyViewModel, MyDto>()
.ForMember(s => s.MyProperty, opt => opt.ResolveUsing<CustomResolver>());

And this is my CustomResolver class (that aims to solve a value through the Claims):

public class CustomResolver : IValueResolver<object, object, string>
{
    private readonly HttpContext _context;

    public CompanyResolver(IHttpContextAccessor httpContextAccessor)
    {
        _context = httpContextAccessor.HttpContext;
    }

    public string Resolve(object source, object destination, string destMember, ResolutionContext context)
    {
        return "I will return here a value from Claims inside _context";
    }
}

Obviously, on my Startup class I registered my Services:

services.AddTransient<IHttpContextAccessor, HttpContextAccessor>();

But, Always, I received this exception from Automapper:

No parameterless constructor defined for this object.

But, precisely, I want the request to go through the constructor (CustomResolver) with parameters because I want to receive IHttpContextAccesor instance.

What's wrong? Why is NET Core not capable of injecting the interface?

回答1:

I solved the problem by changing this:

var automapperConfig = new MapperConfiguration(configuration =>
{
    configuration.AddProfile(new MyProfile());
});

var autoMapper = automapperConfig.CreateMapper();
services.AddSingleton(autoMapper);

To this:

services.AddAutoMapper(configuration =>
{
    configuration.AddProfile(new MyProfile());
});

I do not understand 100% the reason but I guess we should not add Automapper as Singleton