Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • kapil 11 posts 83 karma points
    1 week ago
    kapil
    0

    how to inject and use Automapper in Umbraco applications

    Hi,

    I want to use Automapper to map Class objects (DTO to ViewModel and ViewModel to DTO). May I know how we inject automapper so that we don't have to do manual mappings ?

    public class EmployeeListViewModel
        {
            public int Id { get; set; }
            public string Name { get; set; }
        }
    
    public class EmployeeListDto
        {
            public int Id { get; set; }
            public string Name { get; set; }
            public EmployeeWorkLocationDto EmployeeWorkLocationDto { get; set; }
        }
    
    using AutoMapper;
        public class EmployeeController : SurfaceController
        {
           private readonly IMapper _mapper;
    public EmployeeController(IEmployeeUmbracoService EmployeeUmbracoService, IMapper mapper)
            {
                _EmployeeUmbracoService = EmployeeUmbracoService;
                _mapper = mapper;
            }
        }
    

    When I try to use automapper and inject in the constructor, I get below error:

    Unresolved dependency [Target Type: Test.Controllers.EmployeeController], [Parameter: mapper(AutoMapper.IMapper)], [Requested dependency: ServiceType:AutoMapper.IMapper, ServiceName:]
    
  • DigitallyMedia - Umbraco Specialist 91 posts 360 karma points
    1 week ago
    DigitallyMedia - Umbraco Specialist
    0

    You need to first register automapping in ApplicationStarted

        protected override void ApplicationStarted(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext) {
    
            AutoMapperConfig.RegisterMappings();
    

    ... }

    public static class AutoMapperConfig
    {
        public static void RegisterMappings()
        {
            AutoMapper.Mapper.Configuration.AllowNullCollections = true;
    
       // Create a reference between table and ViewModel
            AutoMapper.Mapper.CreateMap<EmployeeListDto, EmployeeListViewModel>()
                .ForMember(dest => dest.Id, map => map.MapFrom(src => src.Name))
                .ForMember(dest => dest.Body, map => map.MapFrom(src => src.Name))
    }
    }
    

    using AutoMapper; public class EmployeeController : SurfaceController { // Now you can convert EmployeeListDto results to EmployeeListViewModel using single call. public EmployeeListViewModel EmployeeResults(EmployeeListDto list) { var result = Mapper.Map

Please Sign in or register to post replies

Write your reply to:

Draft