Skip to content

Instantly share code, notes, and snippets.

@brentmaxwell
Last active December 6, 2017 14:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brentmaxwell/c4dce0b7b4a46ac392a9 to your computer and use it in GitHub Desktop.
Save brentmaxwell/c4dce0b7b4a46ac392a9 to your computer and use it in GitHub Desktop.
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