3

I want to use automapper to create absolute url using Automappers profile. What is best practice of doing it?

  • My profiles are autoconfigured during startup.
  • I am using an Ioc Container if that might help.

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

In some way I dynamically want to pick up the request base url ("http://www.thisiswhatiwant.com/") to make it possible to put it together with my relativeurl. I know one way of doing it but it is not pretty, ie can't be the best way.

Per
  • 1,393
  • 16
  • 28
  • 1
    I think that's an anti-pattern, because mappers are supposed to be dumb, and thus you might want to resist the temptation of putting too much logic inside them. – Alexandru Marculescu Oct 02 '16 at 07:31
  • 1
    Yes, you are right in that sense, they should be quite dumb. Map from one thing to another. Thing is that I want to expose full links to other resources in my api and therefore I need that base url as well. One solution would be to "extend" my Source object (ie SourceWithContext) and include the base url as context when mapping. That means mapping will be from a source to a destination only. The concatenation need to be done somewhere... – Per Oct 02 '16 at 11:07

1 Answers1

1

I don't know whether this is what you are looking for:

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/");       
    }
}
Silly John
  • 1,584
  • 2
  • 16
  • 34