我已设置个人资料:
builder.Services
.AddAutoMapper((IMapperConfigurationExpression a) => {
a.AddProfile<GeneralMappingProfile>();
});
这是简介:
public class GeneralMappingProfile : Profile
{
public GeneralMappingProfile()
{
CreateMap<Source, Destination>()
.AfterMap<SourceToDestinationAction>()
.ForAllMembers(x => x.Ignore());
}
}
我的操作如下所示:
public class SourceToDestinationAction : IMappingAction<Source, Destination>
{
private readonly IACoolService coolService;
public SourceToDestinationAction(IACoolService _coolService){
coolService = _coolService;
}
public void Process(Source source, Destination destination, ResolutionContext context)
{
destination.Title = coolService.MakeMultiLanguageValue(source.Title);
}
}
我想这样使用它:
...(IMapper mapper){
...
Destination destinationData = mapper.Map<Destination>(sourceData);
}
这不起作用,因为 Action 是无参数构造函数。
如何在我的操作中建立依赖关系?
系统信息:
审核注意事项:
我不确定您使用的是什么版本,但文档说您确实可以执行此操作。这句话看起来和你想做的一模一样:
Asp.Net Core 和 AutoMapper.Extensions.Microsoft.DependencyInjection
如果您使用Asp.Net Core和AutoMapper.Extensions.Microsoft.DependencyInjection包,这也是使用依赖注入的好方法。您无法将依赖项注入到 Profile 类中,但可以在 IMappingAction 实现中做到这一点。
以下示例展示了如何利用依赖注入,在映射操作之后将访问当前 HttpContext 的 IMappingAction 连接到配置文件:
public class SetTraceIdentifierAction : IMappingAction<SomeModel, SomeOtherModel>
{
private readonly IHttpContextAccessor _httpContextAccessor;
public SetTraceIdentifierAction(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor ?? throw new ArgumentNullException(nameof(httpContextAccessor));
}
public void Process(SomeModel source, SomeOtherModel destination, ResolutionContext context)
{
destination.TraceIdentifier = _httpContextAccessor.HttpContext.TraceIdentifier;
}
}
public class SomeProfile : Profile
{
public SomeProfile()
{
CreateMap<SomeModel, SomeOtherModel>()
.AfterMap<SetTraceIdentifierAction>();
}
}