|
1 | 1 | using AspnetRun.Application.Models;
|
2 | 2 | using AspnetRun.Core.Entities;
|
3 | 3 | using AutoMapper;
|
| 4 | +using System; |
4 | 5 |
|
5 | 6 | namespace AspnetRun.Application.Mapper
|
6 | 7 | {
|
7 | 8 | // The best implementation of AutoMapper for class libraries - https://stackoverflow.com/questions/26458731/how-to-configure-auto-mapper-in-class-library-project
|
8 | 9 | public class ObjectMapper
|
9 | 10 | {
|
10 |
| - public static IMapper Mapper |
| 11 | + private static readonly Lazy<IMapper> Lazy = new Lazy<IMapper>(() => |
11 | 12 | {
|
12 |
| - get |
| 13 | + var config = new MapperConfiguration(cfg => |
13 | 14 | {
|
14 |
| - return AutoMapper.Mapper.Instance; |
15 |
| - } |
16 |
| - } |
17 |
| - static ObjectMapper() |
18 |
| - { |
19 |
| - CreateMap(); |
20 |
| - } |
21 |
| - |
22 |
| - private static void CreateMap() |
| 15 | + // This line ensures that internal properties are also mapped over. |
| 16 | + cfg.ShouldMapProperty = p => p.GetMethod.IsPublic || p.GetMethod.IsAssembly; |
| 17 | + cfg.AddProfile<AspnetRunDtoMapper>(); |
| 18 | + }); |
| 19 | + var mapper = config.CreateMapper(); |
| 20 | + return mapper; |
| 21 | + }); |
| 22 | + public static IMapper Mapper => Lazy.Value; |
| 23 | + |
| 24 | + public class AspnetRunDtoMapper : Profile |
23 | 25 | {
|
24 |
| - AutoMapper.Mapper.Initialize(cfg => |
| 26 | + public AspnetRunDtoMapper() |
25 | 27 | {
|
26 |
| - cfg.CreateMap<Product, ProductModel>() |
| 28 | + CreateMap<Product, ProductModel>() |
27 | 29 | .ForMember(dest => dest.Name, opt => opt.MapFrom(src => src.Name)).ReverseMap();
|
28 |
| - cfg.CreateMap<Category, CategoryModel>().ReverseMap(); |
29 |
| - cfg.CreateMap<Wishlist, WishlistModel>().ReverseMap(); |
30 |
| - cfg.CreateMap<Compare, CompareModel>().ReverseMap(); |
31 |
| - cfg.CreateMap<Order, OrderModel>().ReverseMap(); |
32 |
| - }); |
| 30 | + |
| 31 | + CreateMap<Category, CategoryModel>().ReverseMap(); |
| 32 | + CreateMap<Wishlist, WishlistModel>().ReverseMap(); |
| 33 | + CreateMap<Compare, CompareModel>().ReverseMap(); |
| 34 | + CreateMap<Order, OrderModel>().ReverseMap(); |
| 35 | + } |
33 | 36 | }
|
34 | 37 | }
|
35 | 38 | }
|
0 commit comments