Skip to content

Instantly share code, notes, and snippets.

@Magik3a
Last active October 17, 2018 20:03
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 Magik3a/5cb778709d635e83191646f3b59f5d3a to your computer and use it in GitHub Desktop.
Save Magik3a/5cb778709d635e83191646f3b59f5d3a to your computer and use it in GitHub Desktop.
Automapper Generic Mapping on asp .net
namespace Multi_Language.MVCClient
{
using AutoMapper;
using Multi_language.Common.Infrastructure.Mapping;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
public static class AutoMapperConfig
{
public static void RegisterMappings(params Assembly[] assemblies)
{
var types = new List<Type>();
foreach (var assembly in assemblies)
{
types.AddRange(assembly.GetExportedTypes());
}
Mapper.Initialize(s =>
{
LoadStandardMappings(s, types);
LoadCustomMappings(s, types);
});
}
private static void LoadStandardMappings(IMapperConfigurationExpression conf, IEnumerable<Type> types)
{
var maps = types.SelectMany(t => t.GetInterfaces(), (t, i) => new { t, i })
.Where(
type =>
type.i.IsGenericType && type.i.GetGenericTypeDefinition() == typeof(IMapFrom<>) &&
!type.t.IsAbstract
&& !type.t.IsInterface)
.Select(type => new { Source = type.i.GetGenericArguments()[0], Destination = type.t });
foreach (var map in maps)
{
conf.CreateMap(map.Source, map.Destination);
conf.CreateMap(map.Source, map.Destination).ReverseMap();
conf.CreateMissingTypeMaps = true;
}
}
private static void LoadCustomMappings(IMapperConfigurationExpression conf, IEnumerable<Type> types)
{
var maps =
types.SelectMany(t => t.GetInterfaces(), (t, i) => new { t, i })
.Where(
type =>
typeof(ICustomMapping).IsAssignableFrom(type.t) && !type.t.IsAbstract &&
!type.t.IsInterface)
.Select(type => (ICustomMapping)Activator.CreateInstance(type.t));
foreach (var map in maps)
{
map.CreateMappings(conf);
}
}
}
}
using Multi_language.Common.Infrastructure.Mapping;
using Multi_language.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using AutoMapper;
namespace Multi_Language.DataApi.Models
{
public class PhrasesApiModel: IMapFrom<Phrases>, ICustomMapping
{
public int IdProject { get; set; }
public string LanguageInitials { get; set; }
public int IdPhraseContext { get; set; }
public string PhraseText { get; set; }
public void CreateMappings(IMapperConfigurationExpression config)
{
config.CreateMap<Phrases, PhrasesApiModel>()
.ForMember(p => p.IdProject , opt => opt.MapFrom(p => p.PhraseContext.IdProject));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment