0

I'm working on an WebApi project, where I'm using Automapper to map certain Dto's to Entities. So far i needed only one dependency injected for manually mapping a certain property. Now I want to inhject another dependency. My constructor in the AutoMapper class looks like this:

public MapperConfig(
    IRoleRepository roleRepository, IActivityRepository activityRepository)

However, I have trouble instatiating the MapperConfig class in the Startup.cs :

services.AddSingleton<IMapper>(provider => new MapperConfiguration(cfg =>
{
    cfg.AddProfile(new MapperConfig(
        services
            .BuildServiceProvider()
            .GetService<IRoleRepository, IActivityRepository>()));            
}).CreateMapper());

So far I had no problems using the GetService method, because I was passing only one dependency. But if the constructor of the automapper takes multiple parameters, I don't know how to invoke it properly. Any help will be appreciated. Thank you for your time.

Steven
  • 166,672
  • 24
  • 332
  • 435
LeRamme
  • 29
  • 5
  • 2
    https://docs.automapper.org/en/latest/Dependency-injection.html#asp-net-core – Lucian Bargaoanu Apr 23 '21 at 07:11
  • 2
    Calling `BuildServiceProvider` can lead to a wide range of nasty problems such as [Captive Dependencies](https://blog.ploeh.dk/2014/06/02/captive-dependency/), [Torn Lifestyles](https://simpleinjector.org/diatl), memory leaks, and performance problems. See [this answer](https://stackoverflow.com/questions/56042989/what-are-the-costs-and-possible-side-effects-of-calling-buildserviceprovider-i/56058498#56058498). – Steven Apr 23 '21 at 08:25

0 Answers0