Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AutoMapper TypeConverter custom constructor

Hi I am using AutoMapper to move from a Model to a Dto and it's working great. In one TypeConverter I need to inject an Interface (a service) that has to be used by the type converter in order to do the conversion.

How can I accomplish this in AutoMapper?

like image 849
Raffaeu Avatar asked Nov 19 '10 16:11

Raffaeu


1 Answers

Can you not just create a constructor on your TypeConverter class, accepting the service? Rather than using the generic ConvertUsing, pass in a new instance of your TypeConverter constructed with the service...

    public class MyTypeConverter : TypeConverter<String, String>
    {
        public MyTypeConverter(IMyService service)
        {
            MyService = service;
        }

        public IMyService MyService { get; set; }

        protected override string  ConvertCore(string source)
        {
            //use service
        }
     }

Usage:

     Mapper.CreateMap<string, string>()
                     .ConvertUsing(new MyTypeConverter(_myService));
like image 119
Pero P. Avatar answered Sep 22 '22 06:09

Pero P.