Search code examples
c#asp.net-identityautomapperautomapper-5

Ignoring unmapped members after ConvertUsing


this is my code :

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)
            }
        };
    }
}

Note that ApplicationUsers is inherited from IdentityUser Class.

When I tested this mapping,I got this error :

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

I know this error is for that some members are not ignored. Something like this

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

will help me because by default ignore rest of the members but the problem is that if I want to use this kind of code, I cant encrypt my members because I don't access to DI configuration for profile.Because profile is parameter less.

I need something similar to upper code that can implement in ITypeConverter functions.

Anyone has any solution ?


Solution

  • refer to this link GitHub Issue

    that I asked my self,I got my answer :

    In my test I must define the profile like this :

     services.AddAutoMapper(typeof(UserProfile));