Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.