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 come into a situation where you need business logic from other services while you are mapping. For that we will have to inject these services into our 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.

1
2
3
4
5
6
7
8
9
10
11
12
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 trick, for registering also the ones with injected parameters:

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

Thats it. You now can add one or more dependencies into your Profiles and use them for some extra business logic while mapping your objects.

comments powered by Disqus