From 1af2c25f9a41c1d6a35621614f748d0563259f40 Mon Sep 17 00:00:00 2001 From: Jimmy Bogard Date: Sat, 21 Feb 2026 16:47:39 -0600 Subject: [PATCH] Fixing bug around order of open generic registration --- src/AutoMapper/ProfileMap.cs | 2 +- .../Bug/OpenGenericInheritanceOrder.cs | 40 +++++++++++++++++++ 2 files changed, 41 insertions(+), 1 deletion(-) create mode 100644 src/UnitTests/Bug/OpenGenericInheritanceOrder.cs diff --git a/src/AutoMapper/ProfileMap.cs b/src/AutoMapper/ProfileMap.cs index a4ed1c3bdd..d76d4c2f15 100644 --- a/src/AutoMapper/ProfileMap.cs +++ b/src/AutoMapper/ProfileMap.cs @@ -171,7 +171,7 @@ public void Configure(IGlobalConfiguration configuration) } private void Configure(TypeMapConfiguration typeMapConfiguration, IGlobalConfiguration configuration) { - var typeMap = typeMapConfiguration.TypeMap; + var typeMap = configuration.FindTypeMapFor(typeMapConfiguration.Types); if (typeMap.IncludeAllDerivedTypes) { IncludeAllDerived(configuration, typeMap); diff --git a/src/UnitTests/Bug/OpenGenericInheritanceOrder.cs b/src/UnitTests/Bug/OpenGenericInheritanceOrder.cs new file mode 100644 index 0000000000..acacba2325 --- /dev/null +++ b/src/UnitTests/Bug/OpenGenericInheritanceOrder.cs @@ -0,0 +1,40 @@ +namespace AutoMapper.UnitTests.Bug; + +public class OpenGenericInheritanceOrder +{ + class FooBar { } + class SourceBase { public string Name { get; set; } } + class DestinationBase { public string Name { get; set; } } + class SourceDerived : SourceBase { } + class DestinationDerived : DestinationBase { } + + [Fact] + public void Should_work_when_derived_map_declared_before_open_generic_base_map() + { + var config = new MapperConfiguration(cfg => + { + cfg.CreateMap() + .IncludeBase, DestinationBase>(); + cfg.CreateMap(typeof(SourceBase<>), typeof(DestinationBase)); + }); + + var mapper = config.CreateMapper(); + var result = mapper.Map(new SourceDerived { Name = "test" }); + result.Name.ShouldBe("test"); + } + + [Fact] + public void Should_work_when_open_generic_base_map_declared_first() + { + var config = new MapperConfiguration(cfg => + { + cfg.CreateMap(typeof(SourceBase<>), typeof(DestinationBase)); + cfg.CreateMap() + .IncludeBase, DestinationBase>(); + }); + + var mapper = config.CreateMapper(); + var result = mapper.Map(new SourceDerived { Name = "test" }); + result.Name.ShouldBe("test"); + } +}