这是我的代码:
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 继承自 IdentityUser 类。
当我测试这个映射时,我得到了这个错误:
System.NullReferenceException:对象引用未设置为对象的实例。
我知道这个错误是因为某些成员没有被忽略。像这样的东西
CreateMap<UserViewModel ,ApplicationUsers >()
.ConvertUsing(converter=> new ApplicationUsers(){
Email = converter.Email,
....
});
会帮助我,因为默认情况下会忽略其他成员,但问题是如果我想使用这种代码,我无法加密我的成员,因为我无法访问配置文件的 DI 配置。因为配置文件的参数较少。
我需要类似于可以在 ITypeConverter 函数中实现的上层代码的东西。
任何人有任何解决方案?