AutoMapper mapping properties with private setters

AutoMapper allows now (I am not sure, since when) to map properties with private setters. It is using reflection for creating objects.

Example classes:

public class Person
{
    public string Name { get; set; }
    public string Surname { get; set; }
}


public class PersonDto
{
    public string Fullname { get; private set; }
}

And mapping:

AutoMapper.Mapper.CreateMap<Person, PersonDto>()
    .ForMember(dest => dest.Fullname, conf => conf.MapFrom(src => src.Name + " " + src.Surname));

var p = new Person()
{
    Name = "John",
    Surname = "Doe"
};

var pDto = AutoMapper.Mapper.Map<PersonDto>(p);

AutoMapper will map property with private setter with no problem. If you want to force encapsulation, you need to use IgnoreAllPropertiesWithAnInaccessibleSetter. With this option, all private properties (and other inaccessible) will be ignored.

AutoMapper.Mapper.CreateMap<Person, PersonDto>()
    .ForMember(dest => dest.Fullname, conf => conf.MapFrom(src => src.Name + " " + src.Surname))
    .IgnoreAllPropertiesWithAnInaccessibleSetter();

The problem will emerge, if you will use Silverlight. According to MSDN: https://msdn.microsoft.com/en-us/library/stfy7tfc(v=VS.95).aspx

In Silverlight, you cannot use reflection to access private types and members.

Leave a Comment