AutoMapper / AutoMapper.Extensions.Microsoft.DependencyInjection

MIT License
258 stars 79 forks source link

DI and profiles for mapping with constructors with parameters #141

Closed sanioooook closed 4 years ago

sanioooook commented 4 years ago

It seems this question is repeated in part, but I did not understand the answer, so I ask again. My problem is that I need my own service for mapping, which I thought I would get in the constructor using DI, but when I try mapping, I get an error image

AnswerMappingProfile.cs:

using AutoMapper;
using Entities.Interfaces;
using Entities.Models;
using WebApiQandA.DTO;
using WebApiQandA.Interfaces;

namespace WebApiQandA.MappersProfile
{
    public class AnswerMappingProfile: Profile
    {
        public AnswerMappingProfile(IVoteService voteService, IVoteRepository voteRepository)
        {
            CreateMap<Answer, AnswerDto>()
                .ForMember(dest => dest.Votes,
                    opt => opt
                        .MapFrom(c => voteService.GetVotesByAnswerId(c.Id)));

            CreateMap<AnswerDto, Answer>()
                .ForMember(dest => dest.Votes,
                    opt => opt
                        .MapFrom(c => voteRepository.GetVotesByAnswerId((int)c.Id)));
        }
    }
}

Startup.cs:

services.AddTransient<IUserService, UserService>();
services.AddTransient<ISurveyService, SurveyService>();
services.AddTransient<IAnswerService, AnswerService>();
services.AddTransient<IVoteService, VoteService>();
services.AddAutoMapper(typeof(SurveyMappingProfile), typeof(AnswerMappingProfile), typeof(VoteMappingProfile));

How can I solve this problem?

lbargaoanu commented 2 years ago

https://jimmybogard.com/automapper-usage-guidelines/

X DO NOT inject dependencies into profiles

Profiles are static configuration, and injecting dependencies into them can cause unknown behavior at runtime. If you need to use a dependency, resolve it as part of your mapping operation. You can also have your extension classes (resolvers, type converters, etc.) take dependencies directly.