【问题标题】:Read Claims from Automapper Value Resolver on NET Core从 NET Core 上的 Automapper 值解析器读取声明
【发布时间】:2018-04-13 17:22:08
【问题描述】:

我有一个像这样的自动映射器映射配置文件

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

这是我的 CustomResolver 类(旨在通过声明解决一个值):

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 不能注入接口?

【问题讨论】:

  • @LucianBargaoanu 你能澄清你的答案吗?谢谢
  • @LucianBargaoanu 谢谢,我用你的链接解决了问题

标签: asp.net-core dependency-injection automapper


【解决方案1】:

我通过改变这个解决了问题

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

【讨论】:

    猜你喜欢
    • 2020-10-09
    • 2021-10-26
    • 2022-01-09
    • 2021-02-26
    • 2018-03-04
    • 1970-01-01
    • 2020-01-17
    • 2020-02-17
    • 1970-01-01
    相关资源
    最近更新 更多