Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 12 additions & 2 deletions src/AutoMapper/Configuration/MapperConfiguration.cs
Original file line number Diff line number Diff line change
Expand Up @@ -300,15 +300,25 @@ private TypeMap GetTypeMap(TypePair initialTypes)
static List<Type> GetTypeInheritance(Type type)
{
var interfaces = type.GetInterfaces();
var lastIndex = interfaces.Length - 1;
var types = new List<Type>(interfaces.Length + 2) { type };
Type baseType = type;
while ((baseType = baseType.BaseType) != null)
{
types.Add(baseType);
foreach (var interfaceType in baseType.GetInterfaces())
{
var interfaceIndex = Array.LastIndexOf(interfaces, interfaceType);
if (interfaceIndex != lastIndex)
{
interfaces[interfaceIndex] = interfaces[lastIndex];
interfaces[lastIndex] = interfaceType;
}
}
}
for(int index = interfaces.Length - 1; index >= 0; index--)
foreach (var interfaceType in interfaces)
{
types.Add(interfaces[index]);
types.Add(interfaceType);
}
return types;
}
Expand Down
50 changes: 50 additions & 0 deletions src/UnitTests/InterfaceMapping.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,56 @@
using Xunit;
namespace AutoMapper.UnitTests.InterfaceMapping
{
public class InterfaceInheritance : AutoMapperSpecBase
{
protected override MapperConfiguration CreateConfiguration() => new(cfg =>
{
cfg.CreateMap<Source, IProperties>()
.IncludeBase<Source, IPropertyA>()
.IncludeBase<Source, IPropertyB>();
cfg.CreateMap<Source, IPropertyA>();
cfg.CreateMap<Source, IPropertyB>();
});
[Fact]
public void Should_choose_the_derived_interface()
{
var source = new Source
{
Name = "Name",
PropertyA = "PropertyA",
PropertyB = "PropertyB"
};
var destination = new Target();
Mapper.Map(source, destination);
destination.Name.ShouldBe(source.Name);
destination.PropertyA.ShouldBe(source.PropertyA);
destination.PropertyB.ShouldBe(source.PropertyB);
}
public class Source
{
public string PropertyA { get; set; }
public string PropertyB { get; set; }
public string Name { get; set; }
}
public class Target : IProperties
{
public string PropertyA { get; set; }
public string PropertyB { get; set; }
public string Name { get; set; }
}
public interface IProperties : IPropertyA, IPropertyB
{
string Name { get; set; }
}
public interface IPropertyA
{
string PropertyA { get; set; }
}
public interface IPropertyB
{
string PropertyB { get; set; }
}
}
public class MapToInterface : NonValidatingSpecBase
{
protected override MapperConfiguration CreateConfiguration() => new(c=>c.CreateMap<object, IEnumerable<object>>());
Expand Down