Read Claims from Automapper Value Resolver on NET Core

天大地大妈咪最大 提交于 2019-12-13 03:57:41

问题


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



来源:https://stackoverflow.com/questions/49822221/read-claims-from-automapper-value-resolver-on-net-core

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!