1,安装AutoMapper 和 Autofac
命令:
Install-package AutoMapper
Install-package Autofac
1 using Autofac; 2 using AutoMapper; 3 using AutoMapper.Configuration; 4 using Morningstar.EquityFundamentals.Framework.Db.Chatbot; 5 using Morningstar.EquityFundamentals.Model.Chatbot; 6 7 namespace Morningstar.EquityFundamentals.Framework 8 { 9 public static class ContainerBuilderExtension 10 { 11 public static ContainerBuilder LoadAutoMapper(this ContainerBuilder builder) 12 { 13 builder.RegisterType<MapperConfigurationExpression>().SingleInstance(); 14 builder.Register(m => 15 { 16 var mapperConfigurationExpression = m.Resolve<MapperConfigurationExpression>(); 17 var instance = new MapperConfiguration(mapperConfigurationExpression); 18 return instance; 19 }); 20 builder.Register(m => 21 { 22 var mapperConfiguration = m.Resolve<MapperConfiguration>(); 23 return mapperConfiguration.CreateMapper(); 24 }); 25 return builder; 26 } 27 } 28 29 public class AutoMapperProfile : Profile 30 { 31 public void Mapping(ILifetimeScope scope) 32 { 33 var expression = scope.Resolve<MapperConfigurationExpression>(); 34 expression.CreateMap<AppInfo, AppInfoDto>(); 35 } 36 } 37 38 public static class AutoMapperHelper 39 { 40 public static TDestination Map<TDestination>(object source) 41 { 42 ContainerBuilder builder = new ContainerBuilder(); 43 builder.LoadAutoMapper(); 44 builder.RegisterType<AutoMapperProfile>(); 45 IContainer Container = builder.Build(); 46 47 using var scope = Container.BeginLifetimeScope(); 48 scope.Resolve<AutoMapperProfile>().Mapping(scope); 49 return scope.Resolve<IMapper>().Map<TDestination>(source); 50 } 51 } 52 }
2,使用