Automapper - match a property of an interface type without creating a concrete class
I want to be able to match IFoo.IBar.Name without creating a specific object of type IBar. It's easy to do this with a proxy at the CreateMap: level Mapper.CreateMap<Person, IFoo>()
, but how to achieve it for custom backend UI elements?
public class Test
{
[Fact]
public void MapToInnerInterface()
{
const int id = 1;
const string name = "Peter";
var person = new Person {Id = id, Name = name};
Mapper.CreateMap<Person, IFoo>()
.ForMember(dest => dest.Bar.Name, c => c.MapFrom(src => src.Name));
var mapResult = Mapper.Map<IFoo>(person);
Assert.Equal(id, mapResult.Id);
Assert.Equal(name, mapResult.Bar.Name);
}
}
public interface IFoo
{
int Id { get; set; }
IBar Bar { get; set; }
}
public interface IBar
{
string Name { get; set; }
}
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
}
source to share
You can do this by comparing the outer class ( Person
) with an internal interface ( IBar
), and then using this map in a map Person
→ IFoo
.
Mapper.CreateMap<Person, IFoo>()
.ForMember(dest => dest.Bar, opt => opt.MapFrom(src => src));
Mapper.CreateMap<Person, IBar>();
IFoo foo = Mapper.Map<IFoo>(person);
Console.WriteLine(foo.Bar.Name); // Peter
Console.WriteLine(foo.Id); // 1
Two proxy objects are created, one of which implements IFoo
and the other implements IBar
, as you would expect.
Example: https://dotnetfiddle.net/VuyT1K
source to share
I want to be able to map to IFoo.IBar.Name without creating a specific object of type IBar myself
And how do you expect AutoMapper to know which specific type to use for the interface IBar
? As you know, you cannot have an instance of an interface. And someone has to point out which particular type is, and which is definitely not what AutoMapper is capable of doing.
You must use a custom converter on the type IBar
or AfterMap
to specify how this mapping should be done.
source to share