我正在使用带有.NET Core 2.0的AutoMapper 6.2.2及其默认的依赖注入机制来映射模型和DTO。我在AutoMapper配置中需要DI,因为我必须执行需要一些注入组件的AfterMap<Action>
。
问题是,对于某些具有参数匹配某些源成员的构造函数的模型,当我为AutoMapper启用DI(添加services.AddAutoMapper()
)时,这些构造函数默认调用并提供数据,然后使用EF中断我的操作。
public class UserDTO
{
public string Name { get; set; }
public string Email { get; set; }
public ICollection<RoleDTO> Roles { get; set; }
}
public class User
{
public string Name { get; set; }
public string Email { get; set; }
public ICollection<RoleInUser> RoleInUsers { get; } = new List<RoleInUser>();
public ICollection<Role> Roles { get; }
public User()
{
Roles = new JoinCollectionFacade<Role, User, RoleInUser>(this, RoleInUsers);
}
public User(string name, string email, ICollection<Role> roles) : this()
{
Roles.AddRange(roles);
}
}
public class UserProfile : Profile
{
public UserProfile()
{
CreateMap<UserDTO, User>()
.ForMember(entity => entity.Roles, opt => opt.Ignore())
.AfterMap<SomeAction>();
}
}
在前面的代码片段中,User(name, email, roles)
被调用角色列表。
我的映射器配置如下(注意DisableConstructorMapping()
选项)
protected override MapperConfiguration CreateConfiguration()
{
var config = new MapperConfiguration(cfg =>
{
cfg.DisableConstructorMapping();
// Add all profiles in current assembly
cfg.AddProfiles(Assemblies);
});
return config;
}
我的Startup
所有设置:
var mapperProvider = new MapperProvider();
services.AddSingleton<IMapper>(mapperProvider.GetMapper());
services.AddAutoMapper(mapperProvider.Assemblies);
修改配置文件以配置与ConstructUsing
一起使用的ctor
public UserProfile()
{
CreateMap<UserDTO, User>()
.ForMember(entity => entity.Roles, opt => opt.Ignore())
.ConstructUsing(src => new User())
.AfterMap<SomeAction>();
}
它按预期工作,但这迫使我在每个Map配置中包含这个样板语句,并且模型非常大。
没有依赖注入(这需要最近出现),它与第一个片段(不需要ConstructUsing
)顺利运行。
我搜索过这个场景,但没有找到任何东西。是否将ConstructUsing
添加到每个Map中?还有更好的选择吗?或许我做的事情完全错了......
一年后,我在AutoMapper 8.0.0中遇到了这个问题。如果有人仍然关注这个,有两种方法:
ConstructUsing
添加到您的每个CreateMap<Src, Des>
。ConfigureServices
这一行:services.AddAutoMapper(cfg => cfg.DisableConstructorMapping());
但是你必须在每个需要映射的类中创建一个空白构造函数。