60

I need to use a service layer in the AutoMapper profile class in ASP.NET Core but when I inject service in the constructor it does not work. For example:

public class UserProfile : Profile
{
    private readonly IUserManager _userManager;

    public UserProfile(IUserManager userManager)
    {
        _userManager = userManager;

        CreateMap<User, UserViewModel>()
           .ForMember(dest => dest.FullName, opt => opt.MapFrom(src => $"{src.FirstName} {src.LastName}"));
    }
}

And in Startup Class:

 public class Startup
{
    public IConfigurationRoot Configuration { set; get; }

    public Startup(IHostingEnvironment env)
    {
       //some code
    }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddSingleton<IActionContextAccessor, ActionContextAccessor>();
        services.AddMvc();
        services.AddScoped<IUsersPhotoService, UsersPhotoService>();
        services.AddAutoMapper(typeof(UserProfile));
    }
}

How do to do it?

6

5 Answers 5

92

To solve your problem you just need to wire IUserManager in DI, and make sure UserProfile dependency is resolved.

public void ConfigureServices(IServiceCollection services)
{
    // ...
    services.AddSingleton<IUserManager, UserManager>();
    services.AddSingleton(provider => new MapperConfiguration(cfg =>
    {
        cfg.AddProfile(new UserProfile(provider.GetService<IUserManager>()));
    }).CreateMapper());
}

And having that said, I would probably try to keep single responsibility per class, and not have any services injected into mapping profiles. You can populate your objects just before the mapping instead. This way it might be easier to unit test as well.

9
  • 3
    Are there any ways to make it more convenient (e.g. container integration) instead calling provider.GetService<T>() with respect to a container's lifecycle? Mar 12, 2018 at 12:50
  • 1
    You said you wouldn't inject any services into mapping profiles, but what about ILogger services to log mapping warnings inside ConstructUsing(...) maps?
    – jasdefer
    Jan 19, 2021 at 8:44
  • There is always an edgecase :) It depends on your case but maybe you could log a warning after the mapping is done if some values are outside of the expected range. Of course, it might depend on the specific case.
    – Ignas
    Jan 19, 2021 at 9:47
  • 1
    @Ignas, how do mean to populate the objects just before calling the _mapper.Map<origin, destination>(content)? Mar 3, 2021 at 15:07
  • 1
    Very good advice about Single-responsibility principle. "You can populate your objects just before the mapping instead."
    – Jaider
    Jul 29, 2021 at 17:28
23

It's better to use custom IValueResolver for this purposes because it is fully supports IServiceCollection integration (using AutoMapper.Extensions.Microsoft.DependencyInjection).

You may need to implement a custom value resolver:

public class UserViewModelValueResolver: IValueResolver<...>
{
    public readonly IUserManager userManager;
    public UserViewModelValueResolver(IUserManager userManager)
    {
        this.userManager = userManager;
    }
    ...
}

And the registration in services may be reduced to:

public void ConfigureServices(IServiceCollection services)
{
    // ...
    services.AddSingleton<IUserManager, UserManager>();
}

Then you can get a mapper instance inside a controller by injecting IMapper via a constructor.

Based on: AutoMapper: Handling Profile Dependencies using Custom Value Resolvers - Tech Net

4
  • 5
    The problem with this approach is that is can't be translated by a LINQ provider. ResolveUsing is not a supported mapping option per the AutoMapper docs. If you try, AutoMapper will just throw System.Exception: Can't resolve this to Queryable Expression
    – Brad M
    Jun 10, 2018 at 12:57
  • 1
    When I try this, my automapper complains that it cannot create an instance of my resolver. Any ideas?
    – Doug Hill
    Sep 22, 2021 at 20:01
  • How can I use this in a unit test? The ValueResolver needs a constructor parameter, but the unit test will not provide it. You could create the instance yourself, but then how do you instruct AutoMapper to use that instance?
    – Tigerware
    Oct 5, 2022 at 15:51
  • @Tigerware What exactly would you like to test? The value resolver itself or the class that is using it? In the first case you simply write the tests for the value resolver and provide the dependency (like IUserManager) using any mocking library (e.g. Moq). In the second case you mock IValueResolver<T> in a class under the test. Oct 9, 2022 at 17:32
3

You can use IMappingAction to inject service in mapper

public class SetSomeAction : IMappingAction<SomeModel, SomeOtherModel>
{
    private readonly IService service;

    public SetSomeAction(IService _service)
    {
        service = _service;
    }

    public void Process(SomeModel source, SomeOtherModel destination, ResolutionContext context)
    {
        //here you can use the service
    }
}

And in automapper profile connect it like this:

public class SomeProfile : Profile
    {
        public SomeProfile()
        {
            CreateMap<SomeModel, SomeOtherModel>()
                .AfterMap<SetSomeAction>();
           //Here just connect IMappingAction with profile
        }
}
1

I get it that this question is not recent but there is a nuget package for this: AutoMapperBuilder.

You can get what you want by replacing this line:

services.AddAutoMapper(typeof(UserProfile));

with these:

services.AddAutoMapperBuilder(builder =>
{
     builder.Profiles.Add(new UserProfile(services.BuildServiceProvider().GetRequiredService<IUserManager>()));
});
2
  • 5
    You shouldn't call BuildServiceProvider from ConfigureServices since that can lead to duplicate singletons and other issues: learn.microsoft.com/en-us/aspnet/core/fundamentals/…
    – Tobias J
    Aug 26, 2021 at 19:43
  • 2
    To second @TobiasJ, use a value resolver and inject whatever service you would like to use in the value resolver constructor.
    – Pascal
    Sep 7, 2021 at 16:00
0

Building on Ignas's solution, with the latest AutoMapper.Extensions.Microsoft.DependencyInjection you can now also simplify a bit using either the Action<IMapperConfigurationExpression> or Action<IServiceProvider, IMapperConfigurationExpression> overloads depending on if you need the service provider to resolve additional dependencies.

Though with the latter there is an ambiguous overload with params Assembly[] and params Type[], and you must also specify the assembly or a type in the assembly where the mapper configuration is defined which will be important for resolving any dependent IValueResolver or other Automapper types used by the profile.

See also https://github.com/AutoMapper/AutoMapper.Extensions.Microsoft.DependencyInjection/blob/master/src/AutoMapper.Extensions.Microsoft.DependencyInjection/ServiceCollectionExtensions.cs

Example:

The following can be added to startup with the domain details tucked away in another service extension class in a separate assembly:


// Startup.cs
// // IServicesCollection services
// ...
services.AddAutoMapper((serviceProvider, mapperConfiguration) =>
{
     services.RegisterYourProfiles(serviceProvider, mapperConfiguration);
}, services.GetYourProfileAssembly();

// In another extension method in your domain assembly:

public static void RegisterYourMapperProfiles(this IServiceCollection services, IServiceProvider serviceProvider,
            IMapperConfigurationExpression mapperConfiguration)
{
    // You can use the serviceProvider to resolve any dependency of your 
    // custom profile classes that need to be part of DI
    mapperConfiguration.AddProfile(new CustomMappingProfile());
}

public static Assembly GetYourProfileAssembly(this IServiceCollection services)
{
     return typeof(CustomMappingProfile).Assembly;
}

Each domain module/assembly can have its own extension method to abstract away the details of the mapper classes.

If you don't need the serviceProvider you can opt for the simpler overload that just passes the IMapperConfigurationExpression :

// IServicesCollection services
services.AddAutoMapper((mapperConfiguration) =>
{
     services.RegisterYourProfiles(mapperConfiguration);
},
services.GetYourProfileAssembly();
);

After writing this it is arguable if this is simpler than the manual setup suggested by Ignas, but it is a way to use AddAutoMapper and still allow DI.

I also agree it is preferable to keep your profiles clean and free of other dependencies, but there may be a source -> destination mapping strategy for some of your destination fields that you want to keep free of Automapper framework dependencies and have the freedom to do a plug and play style via interfaces and DI.

2
  • this approach doesn't work, trying on .net 6 minimal api
    – Madman
    May 4, 2022 at 14:34
  • @Madman See this answer for how to get this approach to work. Essentially, pass in Array.Empty<Type>() as the second parameter rather than typeof(CustomMappingProfile).Assembly. However note that this means you need to specify all your profiles individually - there will be no assembly scanning.
    – devklick
    Nov 15, 2022 at 22:33

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.