在 ConvertUsing 之后忽略未映射的成员

Ignoring unmapped members after ConvertUsing

这是我的代码:

public class UserProfile:Profile
{
    public UserProfile()
    {
        CreateMap<UserViewModel, ApplicationUsers>().ConvertUsing<UserEncryptor>();
    }

}
public class UserEncryptor : ITypeConverter<UserViewModel, ApplicationUsers>
{
    private readonly IConfigurationRoot _configuration;
    public UserEncryptor(IConfigurationRoot configuration)
    {
        _configuration = configuration;
    }

    public ApplicationUsers Convert(UserViewModel source, ApplicationUsers destination, ResolutionContext context)
    {
        if (context==null||source == null) return null;
        var aes = new Common.EncryptionAes(_configuration[key: "Keys:AesKey"]);
        return new ApplicationUsers
        {
            UserName = aes.EncryptAes(source.Username),
            Email = aes.EncryptAes(source.Email),
            PhoneNumber = aes.EncryptAes(source.MobileNumber),
            User = new User
            {
                FirstName = aes.EncryptAes(source.FirstName),
                LastName = aes.EncryptAes(source.LastName),
                Gender = aes.EncryptAes(source.Gender.ToString()),
                ProfileImage = aes.EncryptAes(source.ProfileImage.FileName)
            }
        };
    }
}

注意ApplicationUsers继承自IdentityUserClass。

当我测试这个映射时,我得到了这个错误:

System.NullReferenceException: Object reference not set to an instance of an object.

我知道这个错误是因为某些成员没有被忽略。 像这样

 CreateMap<UserViewModel ,ApplicationUsers >()
.ConvertUsing(converter=> new ApplicationUsers(){
Email = converter.Email,
....
});

会帮助我,因为默认情况下会忽略其余成员,但问题是如果我想使用这种代码,我无法加密我的成员,因为我无法访问 [=29= 的 DI 配置] profile 参数较少。

我需要类似于上层代码的东西,可以在 ITypeConverter 函数中实现。

有人有解决办法吗?

参考这个linkGitHub Issue

我问自己,我得到了答案:

在我的测试中,我必须像这样定义配置文件:

 services.AddAutoMapper(typeof(UserProfile));