3

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?

Kamil
  • 155
  • 2
  • 8
  • If you're using ASP.NET Core, is there a reason you object to using it without DI? – ProgrammingLlama Oct 18 '19 at 07:57
  • 1
    I have a lot of controllers in my project so every time I have to use DI to map objects and I think that AutoMapper should have differents approaches not only DI. – Kamil Oct 18 '19 at 08:05

1 Answers1

10

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.

ProgrammingLlama
  • 36,677
  • 7
  • 67
  • 86