Search code examples
c#asp.net-coreautomapperautomapping

How to use AutoMapper 9 with static implementation without DI?


I want to create static implementation of AutoMapper without dependency injection. I'm using ASP.NET CORE 2.2 and AutoMapper 9. I've found similar topic:

How to use AutoMapper 9.0.0 in Asp.Net Web Api 2 without dependency injection?

Is there any simpler way to create static implementation without DI?


Solution

  • You can simply build a mapper from the mapper configuration. An example is provided in the AutoMapper docs, which I have reproduced here:

    // use cfg to configure AutoMapper
    var config = new MapperConfiguration(cfg => cfg.CreateMap<Order, OrderDto>()); 
    
    var mapper = config.CreateMapper();
    // or
    var mapper = new Mapper(config);
    OrderDto dto = mapper.Map<OrderDto>(order);
    

    Then you could simply set a static field/property somewhere in your project to hold mapper.