MapsterMapper / Mapster

A fast, fun and stimulating object to object Mapper
MIT License
4.32k stars 329 forks source link

Dynamic Configuration Per Request #627

Closed SoranRad closed 1 year ago

SoranRad commented 1 year ago

Hi There I'm going to create multi language web api so I wanna to map some fields to dto depend on lang key value that stored in request header . for Example this is my doamain


public class Brand{
    public string Name_fa {get;set;}
    public string Name_en{get;set;}
}

and here is my Dto


public class BrandDto{
     public string Name {get;set;}
}

if in header request the language was en so Name_en must be map to Name property. and so on.

here is my code that works fine but it ran just for first mapping not for each request

config.Default
     .GetMemberName((model, side) =>
     {
         if (side == MemberSide.Destination)
         {
                if (model.GetCustomAttributes(true)
                    .OfType<MultilingualAttribute>()
                    .Any()
                   )
                {
                    var httpContext = MapContext.Current.GetService<IHttpContextAccessor>();

                    if (httpContext is null)
                        throw new Exception("HttpContext Not Injected");

                    if(httpContext.HttpContext != null && httpContext.HttpContext.Request.Headers.
                           TryGetValue(Languages.LanguageHeaderKey, out var lang))
                        return model.Name + Languages.LanguageSeperation + lang;
                }
         }

         return model.Name;
     });

what should I do to apply this code for every mapping and change the source property map

andrerav commented 1 year ago

Please use Stack Overflow for these kinds of questions :) Thanks for using Mapster!