首页 文章

从.NET Core上的Automapper Value Resolver读取声明

提问于
浏览
0

我有一个Automapper Mapping Profile 这样:

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

这是我的 CustomResolver 类(旨在通过声明来解决 Value ):

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";
    }
}

显然,在我的 Startup 课上我注册了我的服务:

services.AddTransient<IHttpContextAccessor, HttpContextAccessor>();

但是,总是,我从Automapper收到了这个例外:

没有为此对象定义无参数构造函数 .

但是,确切地说,我希望请求通过带有参数的构造函数(CustomResolver),因为我想接收IHttpContextAccesor实例 .

怎么了?为什么.NET Core无法注入接口?

1 回答

  • 0

    solved the problem 通过改变这个:

    var automapperConfig = new MapperConfiguration(configuration =>
    {
        configuration.AddProfile(new MyProfile());
    });
    
    var autoMapper = automapperConfig.CreateMapper();
    services.AddSingleton(autoMapper);
    

    对此:

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

    我不明白100%的原因,但我想我们不应该将Automapper添加为Singleton

相关问题