AutoMapper/AutoMapper — Issue #154: Incorrect constructor is picked when the ctor parameter name is 'type', resulting in an InvalidCastException.
Author: codekaizen
Created: 2011-12-01 21:14:23+00:00
State: open

I've uploaded a [failing test here](https://github.com/codekaizen/AutoMapper/blob/master/src/UnitTests/Bug/CorrectCtorIsPickedOnDestinationType.cs).

The issue is that the destination class has a ctor parameter named 'type'. This causes ```TypeMapFactory.FindTypeMember``` to match the ```GetType``` method of the source instance, since the default mapping strips the 'Get' text and then the name matches. Later, when the destination instance is created, the ```_runtimeCtor(ctorArgs)``` call in ```ConstructorMap``` fails with the ```InvalidCastException``` since, of course the ```System.Type``` coming from ```GetType()``` doesn't match the type of the ctor chosen by param name only.

I was pondering a fix which ultimately does some kind of type-based matching in conjuction with name-based matching, perhaps checking to see if there is a conversion or a map for the param type. However, wondered why this (to me, somewhat obvious) strongly-typed approach wasn't taken to begin with, and realized it may preclude some usage scenarios I'm unaware of.

Here is a stack trace of the resulting runtime mapping exception:

AutoMapper.AutoMapperMappingException : Trying to map AutoMapper.UnitTests.Bug.CorrectCtorIsPickedOnDestinationType+SourceClass to AutoMapper.UnitTests.Bug.CorrectCtorIsPickedOnDestinationType+DestinationClass.
Using mapping configuration for AutoMapper.UnitTests.Bug.CorrectCtorIsPickedOnDestinationType+SourceClass to AutoMapper.UnitTests.Bug.CorrectCtorIsPickedOnDestinationType+DestinationClass
Exception of type 'AutoMapper.AutoMapperMappingException' was thrown.

----> System.InvalidCastException : Specified cast is not valid.

at AutoMapper.MappingEngine.AutoMapper.IMappingEngineRunner.Map(ResolutionContext context) in MappingEngine.cs: line 314
at AutoMapper.MappingEngine.Map(Object source, Type sourceType, Type destinationType, Action`1 opts) in MappingEngine.cs: line 98
at AutoMapper.MappingEngine.Map(Object source, Action`1 opts) in MappingEngine.cs: line 49
at AutoMapper.MappingEngine.Map(Object source) in MappingEngine.cs: line 38
at AutoMapper.Mapper.Map(Object source) in Mapper.cs: line 27
at AutoMapper.UnitTests.Bug.CorrectCtorIsPickedOnDestinationType.Should_pick_a_ctor_which_best_matches() in CorrectCtorIsPickedOnDestinationType.cs: line 31