Home » C# » Automapper » AutoMapper and constructor with parameters

AutoMapper and constructor with parameters

In some use case you are forced to have classes that has constructor with parameters. This is more rare if you are using Entity Framework (EF) because it requires to have parameterless constructor. However, if the scenario occurs, remember that AutoMapper does not have this constrain. In fact, you can have a private parameterless constructor for Entity Framework (EF) and force the use of a public constructor with parameters when using in your code.

First of all, during the mapping configuration, you must use ConstructUsingServiceLocator method.

Mapper.CreateMap<ContestEditableViewModel, Model.Entities.Contest.Contest>()
      .ConstructUsingServiceLocator();

This instruct AutoMapper to check for the option ConstructServicesUsing method that can be provided during the mapping instruction.

Second, when you are using AutoMapper to map between classes, you must specify every parameters.

var model = AutoMapper.Mapper.Map<ContestEditableViewModel, Model.Entities.Contest.Contest>(viewModel
                , options=>options.ConstructServicesUsing(
                    t=>new Model.Entities.Contest.Contest(yourFirstParameter, yourSecondParameter, /*and so on*/)
                )
            );

This way, you can have classes that have parameters and control how to provided them values.

If you like my article, think to buy my annual book, professionally edited by a proofreader. directly from me or on Amazon. I also wrote a TypeScript book called Holistic TypeScript

2 Responses so far.

  1. Jimmy Bogard says:

    Question for you – why not use the overload of Map that takes in an existing source object?

    var contest = new Contest(param1, param2);
    Mapper.Map(sourceViewModel, contest);

    ?

    Originally I added the ConstructUsingServiceLocator option for MVVM as those mapping from Model to ViewModel also had dependencies inside the ViewModel.

    • You are right. This can be done by taking an existing source object. My first thought was that every where, it is AutoMapper that instantiated the model class. To be consistent, I found a way with AutoMapper to still continue to use the same recipe to get the model. But, without a doubt that your suggestion is better since you made AutoMapper 🙂 Is there any drawback to use the service locator like showed in this post?

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.