避免构造函数映射字段

我正在使用带有.NET Core 2.0的AutoMapper 6.2.2及其默认的dependency injection机制来映射模型和DTO。 我在AutoMapper配置中需要DI,因为我必须执行需要一些注入组件的AfterMap

问题是,对于某些具有参数匹配某些源成员的构造函数的模型,当我为AutoMapper启用DI时(添加services.AddAutoMapper() ),这些构造函数默认调用并输入数据,然后用EF中断我的操作。

 public class UserDTO { public string Name { get; set; } public string Email { get; set; } public ICollection Roles { get; set; } } public class User { public string Name { get; set; } public string Email { get; set; } public ICollection RoleInUsers { get; } = new List(); public ICollection Roles { get; } public User() { Roles = new JoinCollectionFacade(this, RoleInUsers); } public User(string name, string email, ICollection roles) : this() { Roles.AddRange(roles); } } public class UserProfile : Profile { public UserProfile() { CreateMap() .ForMember(entity => entity.Roles, opt => opt.Ignore()) .AfterMap(); } } 

在上一个代码段中,将User(name, email, roles)列表调用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(mapperProvider.GetMapper()); services.AddAutoMapper(mapperProvider.Assemblies); 

修改配置文件以配置与ConstructUsing一起使用的ctor

  public UserProfile() { CreateMap() .ForMember(entity => entity.Roles, opt => opt.Ignore()) .ConstructUsing(src => new User()) .AfterMap(); } 

它按预期工作,但这迫使我在每个Map配置中包含此样板语句,并且模型非常大。

没有dependency injection(这需要最近出现),它与第一个片段(不需要ConstructUsing )顺利运行。

我搜索过这个场景,但没找到任何东西。 是否要将ConstructUsing添加到每个Map中? 还有更好的选择吗? 或许我做的事情完全错了……