Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Put automapper configs in model classes NOTE THIS DOES NOT WORK WITH THE LATEST VERSION OF AUTOMAPPER
public class AutoMapperConfig
{
/// <summary>
/// Function that is called in the Global.asax file
/// Runs through and calls each of the functions below, registering the various mappings
/// </summary>
public static void Execute()
{
RegisterOtherMaps();
RegisterMapperHelpers();
var types = Assembly.GetExecutingAssembly().GetExportedTypes();
LoadStandardMappings(types);
LoadCustomMappings(types);
Mapper.AssertConfigurationIsValid();
}
public static void RegisterOtherMaps()
{
}
/// <summary>
/// Custom method that will apply all custom viewmodel mappings properly
/// </summary>
/// <param name="types"></param>
private static void LoadCustomMappings(IEnumerable<Type> types)
{
var maps = (from t in types
from i in t.GetInterfaces()
where typeof(IHaveCustomMappings).IsAssignableFrom(t) &&
!t.IsAbstract &&
!t.IsInterface
select (IHaveCustomMappings)Activator.CreateInstance(t)).ToArray();
foreach (var map in maps)
{
map.CreateMappings(Mapper.Configuration);
}
}
/// <summary>
/// Applies convention over configuration mapping to basic view models in the project
/// As long as the names in the viewmodel match the domain object structure, no configuration will be necessary
/// </summary>
/// <param name="types"></param>
private static void LoadStandardMappings(IEnumerable<Type> types)
{
var maps = (from t in types
from i in t.GetInterfaces()
where i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IMapFrom<>) &&
!t.IsAbstract &&
!t.IsInterface
select new
{
Source = i.GetGenericArguments()[0],
Destination = t
}).ToArray();
foreach (var map in maps)
{
Mapper.CreateMap(map.Source, map.Destination);
}
}
/// <summary>
/// Register any custom conversions here
/// </summary>
private static void RegisterMapperHelpers()
{
Mapper.CreateMap<DateTime?, string>().ConvertUsing<NullableDateTimeToStringConverter>();
}
}
public interface IHaveCustomMappings
{
void CreateMappings(IConfiguration configuration);
}
public interface IMapFrom<T>
{
}
public class NullableDateTimeToStringConverter : ITypeConverter<DateTime?,string>
{
public string Convert(ResolutionContext context)
{
var sourceDate = context.SourceValue as DateTime?;
return sourceDate.HasValue ? sourceDate.Value.ToShortDateString() : "N/A";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment