tags:

views:

32

answers:

0

Using AutoMapper, is it possible to do a type conversion and selectively format the destination value based on a ForMember expression?

  public class TestConverter : ITypeConverter<string, IHtmlString> {
        public IHtmlString Convert(ResolutionContext context) {
            return new MvcHtmlString(context.SourceValue.ToString());
        }
    }

    public class CostFormatter : ValueFormatter<string> {
        protected override string FormatValueCore(string value) {
            return String.Format("${0}", value);
        }
    }

    public class SimpleClass {
        public string Test { get; set; }
    }

    public class SimpleClassDto {
        public IHtmlString Test { get; set; }
    }

    class Program {
        static void Main(string[] args) {

            Mapper.CreateMap<string,
IHtmlString>().ConvertUsing<TestConverter>();

            Mapper
                .CreateMap<SimpleClass, SimpleClassDto>()
                .ForMember(x => x.Test, opts =>
opts.AddFormatter<CostFormatter>());

            var s = new SimpleClass() { Test = "4.56" };
            var dto = Mapper.Map<SimpleClass, SimpleClassDto>(s);

            Console.WriteLine(dto.Test);

        }
    }

What I'm currently seeing is the projection from string to IHtmlString, but the formatter is not hit and the output is 4.56 instead of $4.56.

What am I missing?