How to pass parameters to an AutoMapper Profile constructor aka Dependency Injection for AutoMapper

While using AutoMapper for mapping different objects in your application, you might encounter situations where you need business logic from other services during the mapping process. To handle this, you can inject these services into your Profile class.

Pass the parameters (for example, a service) into the constructor of the Profile, and then you can use them in your CreateMap methods. Here is a quick example:

public class MyAutoMapperProfile : Profile
{
    public MyAutoMapperProfile
    {
    }

    public MyAutoMapperProfile(IMyService myService) 
    {
        CreateMap<myModel, myViewModel>()
            .ForMember(myViewModel => myViewModel.Property1, myModel => _.MapFrom(myService.DoSomething(myModel)));
    }
}

Pay extra attention on the empty constructor, which is also needed.

Then, in the Program.cs of your project, you will have to register all the Profiles using the following approach to include those with injected parameters:

builder.Services.AddAutoMapper(
    (serviceProvider, mapperConfiguration) => 
        mapperConfiguration.AddProfile(new MyAutoMapperProfile(serviceProvider.GetService<IMyService>())),
    AssemblyUtils.LoadAllAssemblies().ToArray()
);

That’s it. You can now add one or more dependencies into your Profiles and use them for additional business logic while mapping your objects.

comments powered by Disqus