My current project with assemblies for the domain model, MVC web application, and unit tests. How can I set up the AutoMapper configuration so that all assemblies reference
I have been moving my AutoMapper CreateMap calls into classes that live beside my view models. They implement an IAutomapperRegistrar interface. I use reflection to find the IAutoMapperRegistrar implementations, create an instance and add the registrations.
Here is the interface:
public interface IAutoMapperRegistrar
{
void RegisterMaps();
}
Here is an implementation of the interface:
public class EventLogRowMaps : IAutoMapperRegistrar
{
public void RegisterMaps()
{
Mapper.CreateMap()
.ConstructUsing(he => new EventLogRow(he.Id))
.ForMember(m => m.EventName, o => o.MapFrom(e => e.Description))
.ForMember(m => m.UserName, o => o.MapFrom(e => e.ExecutedBy.Username))
.ForMember(m => m.DateExecuted, o => o.MapFrom(e => string.Format("{0}", e.DateExecuted.ToShortDateString())));
}
}
Here is the code that performs the registrations in my Application_Start:
foreach (Type foundType in Assembly.GetAssembly(typeof(ISaveableModel)).GetTypes())
{
if(foundType.GetInterfaces().Any(i => i == typeof(IAutoMapperRegistrar)))
{
var constructor = foundType.GetConstructor(Type.EmptyTypes);
if (constructor == null) throw new ArgumentException("We assume all IAutoMapperRegistrar classes have empty constructors.");
((IAutoMapperRegistrar)constructor.Invoke(null)).RegisterMaps();
}
}
I figure it's appropriate and at least a bit logical; they are a lot easier to follow that way. Before I had hundreds of registrations in one huge bootstrap method and that was starting to become a pain in the ass.
Thoughts?