3

Automapper を使用して、Automappers プロファイルを使用して絶対 URL を作成したいと考えています。それを行うためのベストプラクティスは何ですか?

  • プロファイルは起動時に自動構成されます。
  • 役立つ場合は、Ioc コンテナーを使用しています。

    SourceToDestinationProfile : Profile
    {
        public SourceToDestinationProfile()
        {
            var map = CreateMap<Source, Destination>();
    
            map.ForMember(dst => dst.MyAbsoluteUrl, opt => opt.MapFrom(src => "http://www.thisiswhatiwant.com/" + src.MyRelativeUrl));
            ...
        }
    }
    

何らかの方法で、リクエストのベース URL (" http://www.thisiswhatiwant.com/ ")を動的に取得して、相対 URL と一緒に配置できるようにしたいと考えています。私はそれを行う 1 つの方法を知っていますが、きれいではありません。つまり、最善の方法とは言えません。

4

1 に答える 1

1

これがあなたが探しているものかどうかわかりません:

public class Source
{
    public string Value1 { get; set; }

    public string Value2 { get; set; }
}

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

    public string Value2 { get; set; }
}

public class ObjectResolver : IMemberValueResolver<Source, Destination, string, string>
{
    public string Resolve(Source s, Destination d, string source, string dest, ResolutionContext context)
    {
        return (string)context.Items["domainUrl"] + source;
    }
}

public class Program
{
    public void Main()
    {
         var config = new MapperConfiguration(cfg =>
            {
                cfg.CreateMap<Source, Destination>()
                    .ForMember(o => o.Value1, opt => opt.ResolveUsing<ObjectResolver, string>(m=>m.Value1));
            });

            var mapper = config.CreateMapper();
            Source sr = new Source();
            sr.Value1 = "SourceValue1";
            Destination de = new Destination();
            de.Value1 = "dstvalue1";
            mapper.Map(sr, de, opt => opt.Items["domainUrl"] = "http://test.com/");       
    }
}
于 2016-10-04T14:06:55.197 に答える