Thiago Marcolino Thiago Marcolino - 1 month ago 34
C# Question

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);
}
}

Answer

I did do creating a CustomResolver

public class MyProfile : Profile
{

    protected override void Configure()
    {
        CreateMap<Destinantion, 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);
    }
}