Skip to content

Instantly share code, notes, and snippets.

@akimboyko
Created April 24, 2013 04:01
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save akimboyko/5449531 to your computer and use it in GitHub Desktop.
Save akimboyko/5449531 to your computer and use it in GitHub Desktop.
AutoMapper configuration with profilers. Answer for http://stackoverflow.com/questions/16153592/automapper-profiles-and-unit-testing
void Main()
{
var mapping = new AutoMapperConfiguration();
mapping.SelfTest();
mapping.Map<Person, PersonDTO>(new Person { FullName = "Ola Hansen" }).Dump();
mapping.Map<Turtle, TurtleDTO>(new Turtle { NickName = "Tortilla" }).Dump();
}
public class AutoMapperConfiguration
{
private readonly object LockObject = new object();
private volatile bool _isMappinginitialized;
private MappingEngine _mappingEngine;
private void Configure()
{
var configStore = new ConfigurationStore(new TypeMapFactory(), MapperRegistry.AllMappers());
configStore.AddProfile(new ABCMappingProfile());
configStore.AddProfile(new XYZMappingProfile());
_mappingEngine = new MappingEngine(configStore);
_isMappinginitialized = true;
}
public void InitializeMapping()
{
if (!_isMappinginitialized)
{
lock (LockObject)
{
if (!_isMappinginitialized)
{
Configure();
}
}
}
}
public void SelfTest()
{
InitializeMapping();
_mappingEngine.ConfigurationProvider.AssertConfigurationIsValid();
}
public TEntity Map<TSource, TEntity>(TSource source)
where TEntity : class
where TSource : class
{
InitializeMapping();
return _mappingEngine.Map<TSource, TEntity>(source);
}
}
public class ABCMappingProfile : Profile
{
public override string ProfileName
{
get { return "ABCMappingProfile"; }
}
protected override void Configure()
{
CreateMap<Person, PersonDTO>()
.ForMember(d => d.FullName, opt => opt.MapFrom(s => s.FullName));
CreateMap<PersonDTO, Person>()
.ForMember(d => d.FullName, opt => opt.MapFrom(s => s.FullName));
}
}
public class XYZMappingProfile : Profile
{
public override string ProfileName
{
get { return "XYZMappingProfile"; }
}
protected override void Configure()
{
CreateMap<Turtle, TurtleDTO>()
.ForMember(d => d.NickName, opt => opt.MapFrom(s => s.NickName));
CreateMap<TurtleDTO, Turtle>()
.ForMember(d => d.NickName, opt => opt.MapFrom(s => s.NickName));
}
}
public class Person { public new string FullName { get; set; } }
public class PersonDTO { public new string FullName { get; set; } }
public class Turtle { public new string NickName { get; set; } }
public class TurtleDTO { public new string NickName { get; set; } }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment