How inject service in AutoMapper profile class

前端 未结 3 2088
渐次进展
渐次进展 2020-12-29 05:00

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 ex

相关标签:
3条回答
  • 2020-12-29 05:16

    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>()));
    });
    
    0 讨论(0)
  • 2020-12-29 05:26

    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.

    0 讨论(0)
  • 2020-12-29 05:32

    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

    0 讨论(0)
提交回复
热议问题