Thiago Marcolino
Thiago Marcolino

Reputation: 121

AutoMapper - How to pass parameters to Profile?

I'd like to use automapper to map between my public data contracts and my BD model. And I need to pass a string parameter into my MapProfile and get a description from my property ("Code" in this example). For example:

public class Source
{
    public int Code { get; set; }
}

public class Destination
{
    public string Description { get; set; }
}

public class Dic
{
    public static string GetDescription(int code, string tag)
    {
            //do something
            return "My Description";
    }
}

public class MyProfile : Profile
{

    protected override void Configure()
    {
        CreateMap<Destination, Source>()
            .ForMember(dest => dest.Description, 
                opt => /* something */ 
                Dic.GetDescription(code, tag));
    }
}

public class MyTest 
{

        [Fact]
        public void test()
        {
            var source = new Source { Code = 1};

            var mapperConfig = new MapperConfiguration(config => config.AddProfile<MyProfile>());
            var mapper = mapperConfig.CreateMapper();

            var result = mapper.Map<Destination>(source, opt => opt.Items["Tag"] = "AnyTag");

            Assert.Equal("My Description", result.Description);
        }
}

Upvotes: 4

Views: 13056

Answers (2)

A.R.B
A.R.B

Reputation: 101

Passing in key-value to Mapper

When calling map you can pass in extra objects by using key-value and using a custom resolver to get the object from context.

mapper.Map<Source, Dest>(src, opt => opt.Items["Foo"] = "Bar");

This is how to setup the mapping for this custom resolver

cfg.CreateMap<Source, Dest>()
    .ForMember(dest => dest.Foo, opt => opt.MapFrom((src, dest, destMember, context) => context.Items["Foo"]));

From : https://docs.automapper.org/en/stable/Custom-value-resolvers.html

Upvotes: 5

Thiago Marcolino
Thiago Marcolino

Reputation: 121

This can be achieved using a CustomResolver

public class MyProfile : Profile
{

    protected override void Configure()
    {
        CreateMap<Destination, Source>()
            .ForMember(dest => dest.Description, opt => opt.ResolveUsing<CustomResolver>().FromMember(src => src.Code));
    }
}

public class CustomResolver : IValueResolver
{
    public ResolutionResult Resolve(ResolutionResult source)
    {
        var code = (int)source.Value;

        var tag = source.Context.Options.Items["Tag"].ToString();

        var description = Dic.GetDescription(code, tag);

        return source.New(description);
    }
}

Upvotes: 6

Related Questions