locked
Automapper 8.1.1 how to configure RRS feed

  • Question

  • User-1104215994 posted

    Hi,

    I would like to use <g class="gr_ gr_30 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling" id="30" data-gr-id="30">automapper</g> in order to transform <g class="gr_ gr_65 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling ins-del multiReplace" id="65" data-gr-id="65">dto</g> to entities. I followed this article (https://www.infoworld.com/article/3192900/how-to-work-with-automapper-in-c.html) but couldn't figure it out where to put MapperConfiguration. Any help would be great.

    Here <g class="gr_ gr_224 gr-alert gr_gramm gr_inline_cards gr_run_anim Grammar multiReplace" id="224" data-gr-id="224">is</g> my Business Services:

    public async Task<GameConfirmResponse> GamePurchase(RequestDto requestDto)
            {
                using (var scope = new TransactionScope())
                {
                    //Unique reference ID
                    var game = new GameRequest {referenceId = Guid.NewGuid().ToString()};
                    //Transform DTO into GameRequest for calling Razer Initiate
                    var gameRequest = Mapper.Map<RequestDto, GameRequest>(requestDto);
                    gameRequest = Utilities.CreateSignature(gameRequest, RequestType.Initiate);
                    //Insert request into database
                    _unitOfWork.GameRepository.Insert(gameRequest);
    
                    #region Call Razer initiate
    
                    var response = await Utilities.CallRazer(gameRequest, "purchaseinitiation");
                    //Read response
                    var htmlResponse = await response.Content.ReadAsStringAsync();
    
                    var gameResponse = JsonConvert.DeserializeObject<GameResponse>(htmlResponse);
                    //Adding response into database
                    _unitOfWork.GameResponseRepository.Insert(gameResponse);
                    
                    if (gameResponse.initiationResultCode == "00")
                    {
    
                    }
                    #endregion
                    await _unitOfWork.SaveAsync();
                    
                    var gameConfirmResponse = Mapper.Map<RequestDto, GameConfirmResponse>(requestDto);
                    scope.Complete();
                    
                    return gameConfirmResponse;
                }
            }

    Sunday, June 30, 2019 9:02 PM

All replies

  • User283571144 posted

    Hi cenk1536,

    I followed this article (https://www.infoworld.com/article/3192900/how-to-work-with-automapper-in-c.html) but couldn't figure it out where to put MapperConfiguration. Any help would be great.

    As far as I know, if you want to use automapper instance API, you could create a class named AutoMapperConfig.cs. 

    Then you could add the Create the AutoMapper Configuration Class and add your mapping profile class here.

    At last, you could directly call the AutoMapper Configuration's method to create the config and then using config.CreateMapper metho to create the mapper.

    More details, you could refer to below codes:

    AutoMapperConfig.cs

        using AutoMapper;
        using System;
        using System.Collections.Generic;
        using System.Linq;
        using System.Web;
         using MVCNormallIssue.Models;
    
        namespace MVCNormallIssue.App_Start
        {
            public class AutoMapperConfig
            {
                //public static void config()
                //{
                //    Mapper.Initialize( cfg => cfg.CreateMap<Author,AuthorDTO>());
                //}
    
                public MapperConfiguration Configure()
                {
                    var config = new MapperConfiguration(cfg =>
                    {
                        //way one 
                        cfg.CreateMap<Author, AuthorDTO>();
                        //way two
                        cfg.AddProfile<AuthorMappingProfile>();
                    }
                   );
    
                    return config;
                }
            }
    
            //way two 
            public class AuthorMappingProfile : Profile
            {
                public AuthorMappingProfile()
                {
                    CreateMap<Author, AuthorDTO>().ReverseMap();
                }
            }
        }

    Controller:

    using AutoMapper;
    using MVCNormallIssue.App_Start;
    using MVCNormallIssue.Models;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    
    namespace MVCNormallIssue.Controllers
    {
        public class AutoMapperTestController : Controller
        {
            // GET: AutoMapperTest
            public ActionResult Index()
            {
                //Obsolete
                //Mapper.Initialize(x => x.CreateMap<Author, AuthorDTO>());
    
                //For member used to customsize the mapper
                // var config = new MapperConfiguration(cfg => { cfg.CreateMap<Author, AuthorDTO>().ForMember(destination => destination.NameAndAge, opts => opts.MapFrom(x => x.Name + "is" + x.Age)); });
    
                var config = new AutoMapperConfig().Configure();
    
                IMapper imapper = config.CreateMapper();
    
                var source = new Author() { Id=1, Age="20", Name="Test1" };
                //way one if the destination object not exists
                var re = imapper.Map<Author, AuthorDTO>(source);
    
                //way two if the destination object is existed
    
                var des = new AuthorDTO();
    
                imapper.Map(source, des);
    
    
    
                return View();
            }
        }
    }

    Best Regards,

    Brando

    Monday, July 1, 2019 6:01 AM
  • User-1104215994 posted

    Hi Brando,

    Can I add multiple maps inside this?

    var config = new MapperConfiguration(cfg =>
                    {
                         
                        cfg.CreateMap<Author, AuthorDTO>();
                       cfg.CreateMap<Game, GameDTO>();
                       cfg.CreateMap<Dog, DogDTO>();
                       
                    }

    I use mapping in <g class="gr_ gr_66 gr-alert gr_gramm gr_inline_cards gr_run_anim Grammar only-ins doubleReplace replaceWithoutSep" id="66" data-gr-id="66">business</g> <g class="gr_ gr_54 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling ins-del multiReplace" id="54" data-gr-id="54">serive</g> layer as follows. Should I create AutoMapperConfig class in this layer?

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Net;
    using System.Net.Http;
    using System.Threading.Tasks;
    using System.Transactions;
    using AutoMapper;
    using BusinessEntities;
    using BusinessService.Utility;
    using DataModels;
    using Newtonsoft.Json;
    
    namespace BusinessService
    {
        public class GameServices : IGameServices
        {
            private readonly UnitOfWork _unitOfWork;
    
            /// <summary>
            /// Public constructor.
            /// </summary>
            public GameServices(UnitOfWork unitOfWork)
            {
                _unitOfWork = unitOfWork;
            }
    
    
            /// <summary>
            /// Creates a game
            /// </summary>
            /// <param name="requestDto"></param>
            /// <returns></returns>
            public async Task<GameConfirmResponse> GamePurchase(RequestDto requestDto)
            {
                using (var scope = new TransactionScope())
                {
    
                    //Transform DTO into GameRequest for calling Razer Initiate
                    var config = new MapperConfiguration(cfg => {
                        cfg.CreateMap<RequestDto, GameRequest>();
                    });
                    
                    var iMapper = config.CreateMapper();
                    var gameRequest = iMapper.Map<RequestDto, GameRequest>(requestDto);
                    //Create signature
                    gameRequest = Utilities.CreateSignature(gameRequest, RequestType.Initiate);
                    //Unique reference ID
                    gameRequest.referenceId = Guid.NewGuid().ToString();
                    try
                    {
                        //Add request into database
                        _unitOfWork.GameRepository.Insert(gameRequest);
                        
                    }
                    catch (Exception e)
                    {
                        
                        throw e;
                    }
                    
    
                    #region Call Razer initiate
    
                    HttpResponseMessage response = null;
                    try
                    {
                        response = await Utilities.CallRazer(gameRequest, "purchaseinitiation");
                    }
                    catch (Exception e)
                    {
                       
                        throw e;
                    }
                   
                    //Read response
                    var htmlResponse = await response.Content.ReadAsStringAsync();
    
                    var gameResponse = JsonConvert.DeserializeObject<GameResponse>(htmlResponse);
                    //Adding response into database
                    _unitOfWork.GameResponseRepository.Insert(gameResponse);
                    
                    if (gameResponse.initiationResultCode == "00")
                    {
                        //Create signature
                        var gameConfirmRequest = Utilities.CreateSignature(gameRequest, RequestType.Confirm);
                    }
                    #endregion
                    await _unitOfWork.SaveAsync();
    
                    var gameConfirmResponse = Mapper.Map<RequestDto, GameConfirmResponse>(requestDto);
                    scope.Complete();
                    
                    return gameConfirmResponse;
                }
            }
    
            
            public enum RequestType
            {
                Initiate = 0,
                Confirm = 1
                
            }
    
        }
    }
    

    Tuesday, July 2, 2019 6:48 AM
  • User-1104215994 posted

    How can I implement DI with Unity? Where to put configuration ?

    //Transform DTO into GameRequest for calling Razer Initiate
    var config = new MapperConfiguration(cfg =>
    {
        cfg.CreateMap<RequestDto, GameRequest>();
        cfg.CreateMap<GameRequest, GameConfirmRequest>();
        cfg.CreateMap<GameConfirmResponse, GameConfirmResponseDto>();
        cfg.CreateMap<Coupon, CouponDto>();
    });
    
    var iMapper = config.CreateMapper();
    var gameRequest = iMapper.Map<RequestDto, GameRequest>(requestDto);

    Wednesday, July 3, 2019 7:35 PM
  • User-769277674 posted

    Hi your answer save my life , I have searching for configuring the Autommaper in my Api for hours after finding your solution , I have a little  Note to say , if I have more than one ActionResult I should in every Action use 

    var config = new AutoMapperConfig().Configure();
    IMapper imapper = config.CreateMapper();

     That will be a repetition  and a memory consumption so you can define the MapperConfiguration and the IMapper interface globaly , and use them in eache Action.

    I have a question do you have a solution to inject the IMapper in the constructor of the controller (DI) I try a lot of example but I find this problem :

    "An error occurred when trying to create a controller of type 'CustomersController'. Make sure that the controller has a parameterless public constructor.",
    Thank you in advance .

    Saturday, May 2, 2020 2:47 AM