Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How inject service in AutoMapper profile class

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?

like image 957
m.shakeri Avatar asked Jul 03 '17 03:07

m.shakeri


People also ask

How does AutoMapper work in C#?

AutoMapper in C# is a library used to map data from one object to another. It acts as a mapper between two objects and transforms one object type into another. It converts the input object of one type to the output object of another type until the latter type follows or maintains the conventions of AutoMapper.


1 Answers

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.

like image 52
Ignas Avatar answered Oct 05 '22 18:10

Ignas