Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automapper and immutability

Is it possible to use AutoMapper with Immutable types?

For example my Domain type is immutable and I want to map my view type to this.

I believe it is not but just want this confirmed.

Also as it is best practice to have your domain types immutable, what is the best practice when mapping your view types to domain types?

like image 249
Noel Avatar asked Feb 03 '10 21:02

Noel


1 Answers

We have immutable objects using the builder pattern. Mapping them takes a little more boilerplate code, but it is possible

// ViewModel
public class CarModel : IVehicleModel 
{
    private CarModel (Builder builder)
    {
        LicensePlate = builder.LicensePlate;
    }    

    public string LicensePlate { get; }

    //
    public Builder
    {
        public string LicensePlate { get; set; }
    }
}


// Model
public class CarViewModel : IVehicleViewModel
{
    private CarViewModel (Builder builder)
    {
        LicensePlate = builder.LicensePlate ;
    }    

    public ILicensePlate LicensePlate { get; }

    //
    public Builder
    {
        public ILicensePlate LicensePlate { get; set; }
    }
}

Our AutoMapper Profiles have three mappings registered:

        CreateMap<IVehicleModel, CarViewModel.Builder>();
        CreateMap<CarViewModel.Builder, IVehicleViewModel>().ConvertUsing(x => x.Build());
        CreateMap<IVehicleModel, IVehicleViewModel>().ConvertUsing<VehicleModelTypeConverter>();

The VehicleModelTypeConverter then defines a two stage conversion:

    public IVehicleViewModel Convert(IVehicleModel source, IVehicleViewModel destination,
        ResolutionContext context)
    {
        var builder = context.Mapper.Map<CarViewModel.Builder>(source);
        var model = context.Mapper.Map<IVehicleViewModel>(builder);

        return model;
    }

(An implementation of ITypeListConverter<string, ILicensePlate> carries out that mapping).

Usage in our system is as normal:

var result = _mapper<IVehicleViewModel>(_carModel);

This is using AutoMapper v7.0.1

like image 60
Morphed Avatar answered Oct 24 '22 08:10

Morphed