我有一个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 回答
我 solved the problem 通过改变这个:
对此:
我不明白100%的原因,但我想我们不应该将Automapper添加为Singleton