I'm using AutoMapper v6.1.1 to map from my rich domain model entities to some flattened DTOs.
I'm initialising the configuration in a static class that returns an IMapper
, which adds our mapping profiles and configures PreserveReferences()
for all our maps.
I have declared a custom attribute against a subset of my source entity members (that only applies to members of type string
).
I would like to add a global configuration to AutoMapper that allows me to call an extension method against any members with that attribute during the mapping.
Each of these members will end up in many different destination types, so I thought it would be a simple way of ensuring the extension method is always run for those members without explicitly configuring it for each new map.
A contrived example follows.
Source entity:
public class SomeEntity
{
public string PropertyWithoutCustomAttribute { get; set; }
[CustomAttribute]
public string PropertyWithCustomAttribute { get; set; }
}
Target entity:
public class SomeEntityDto
{
public string PropertyWithoutCustomAttribute { get; set; }
public string PropertyWithCustomAttribute { get; set; }
}
Extension method:
public static string AppendExclamationMark(this string source)
{
return source + "!";
}
If my source instance is defined with these values:
var source = new SomeEntity
{
PropertyWithoutCustomAttribute = "Hello",
PropertyWithCustomAttribute = "Goodbye"
};
I would expect the following statements to be true:
destination.PropertyWithoutCustomAttribute == "Hello"
destination.PropertyWithCustomAttribute == "Goodbye!"
I have become completely bogged down (and am struggling with the documentation somewhat) but I think the closest I have got is this:
cfg.ForAllPropertyMaps(
map => map.SourceType == typeof(string) &&
map.SourceMember
.GetCustomAttributes(
typeof(CustomAttribute),
true)
.Any(),
(map, configuration) => map.???);
Any help would be greatly appreciated, even if to tell me it's a terrible idea or it's not possible.