using automapper without dependency injection

Solutions on MaxInterview for using automapper without dependency injection by the best coders in the world

showing results for - "using automapper without dependency injection"
Elisa
20 Aug 2018
1public static class MapperWrapper 
2{
3    private const string InvalidOperationMessage = "Mapper not initialized. Call Initialize with appropriate configuration. If you are trying to use mapper instances through a container or otherwise, make sure you do not have any calls to the static Mapper.Map methods, and if you're using ProjectTo or UseAsDataSource extension methods, make sure you pass in the appropriate IConfigurationProvider instance.";
4    private const string AlreadyInitialized = "Mapper already initialized. You must call Initialize once per application domain/process.";
5
6    private static IConfigurationProvider _configuration;
7    private static IMapper _instance;
8
9    private static IConfigurationProvider Configuration
10    {
11        get => _configuration ?? throw new InvalidOperationException(InvalidOperationMessage);
12        set => _configuration = (_configuration == null) ? value : throw new InvalidOperationException(AlreadyInitialized);
13    }
14
15    public static IMapper Mapper
16    {
17        get => _instance ?? throw new InvalidOperationException(InvalidOperationMessage);
18        private set => _instance = value;
19    }
20
21    public static void Initialize(Action<IMapperConfigurationExpression> config)
22    {
23        Initialize(new MapperConfiguration(config));
24    }
25
26    public static void Initialize(MapperConfiguration config)
27    {
28        Configuration = config;
29        Mapper = Configuration.CreateMapper();
30    }
31
32    public static void AssertConfigurationIsValid() => Configuration.AssertConfigurationIsValid();
33}
34