从NET Core上的Automapper Value Resolver读取声明 [英] Read Claims from Automapper Value Resolver on NET Core
问题描述
我有一个自动映射器个人资料,如下所示:
I have a Automapper Mapping Profile like this:
CreateMap<MyViewModel, MyDto>()
.ForMember(s => s.MyProperty, opt => opt.ResolveUsing<CustomResolver>());
这是我的 CustomResolver 类(旨在通过Claims解决值):
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";
}
}
很明显,在我的 Startup 类中,我注册了我的服务:
Obviously, on my Startup class I registered my Services:
services.AddTransient<IHttpContextAccessor, HttpContextAccessor>();
但是,总是,我从Automapper收到此异常:
But, Always, I received this exception from Automapper:
没有为此对象定义无参数的构造函数.
No parameterless constructor defined for this object.
但是,正是因为我想接收IHttpContextAccesor实例,我才希望该请求通过带有参数的构造函数(CustomResolver).
But, precisely, I want the request to go through the constructor (CustomResolver) with parameters because I want to receive IHttpContextAccesor instance.
怎么了?为什么NET Core无法注入接口?
What's wrong? Why is NET Core not capable of injecting the interface?
推荐答案
我通过更改以下内容解决了问题:
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
I do not understand 100% the reason but I guess we should not add Automapper as Singleton
这篇关于从NET Core上的Automapper Value Resolver读取声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!