我有一个关于ASP NET Core中AutoMapper依赖注入的问题 . 我知道在实现自定义 IValueResolverIMemberValueResolver 时,可以使用DI的自动扩展程序 . 仅当自定义值解析器由AutoMapper / DI创建时,此方法才有效 . 不幸的是,如果我需要手动创建值解析器,这不起作用 . 另请注意,当我调用 mapper.Map<>() 方法时,我不想传递项目,因为我不希望 IMapper 的使用者在运行时对任何额外参数有任何意识

请考虑以下代码:

class Entity1
{
    public int MyProperty1 { get; set; } 
}

class Dto1 
{
    public int MyProperty1 { get; set; } 
    public string CustomProperty { get; set; } 
}

在MyProfile.cs中

CreateMap<Entity1, Dto1>()
    .ForMember(x => x.CustomProperty, 
       opt => opt.ResolveUsing(new MyCustomPropertyResolver("Important value")));

而MyCustomPropertyResolver是这样的:

public class MyCustomPropertyResolver : IValueResolver<Entity1, Dto1, string>
{
    string _someValue;
    public MyCustomPropertyResolver(string someValue)
    {
        _someValue = someValue;
    }
    string Resolve(Entity1 source, Dto1 destination, string destMember, ResolutionContext context)
    {
        //I need IHttpContextAccessor ..... How can I do that???
    } 
}

当然,如果我这样做:

CreateMap<Entity1, Dto1>()
    .ForMember(x => x.CustomProperty, 
       opt => opt.ResolveUsing<MyCustomPropertyResolver>()));

我可以使用DI并将 IHttpContextAccessor 添加到 MyCustomPropertyResolver 构造函数,但是我将无法将任何额外的参数传递给解析器,这对于解析实际值也很重要 . 有没有办法实现这个目标?我能够实现这一目标的唯一方法是在 MyProfile 类上添加一个静态属性,并通过 ActionFilter 在服务请求的控制器上设置它 . 虽然这项工作,但我不喜欢这个解决方案,因为它会产生不必要的依赖 . AutoMapper的官方解决方案是这样做:

// This solution is not good enough for my need
var dto = mapper.Map<Dto1>(entity, opt => { opt.Items["AnyThing"] = Whatever; });

使用上面的代码,我可以将 HttpContext 传递给items字典,但这将使mapper使用者需要传入可能不知道的参数 .

我现实中的代码要复杂得多,但它在概念上使用了上面的相同示例 .