Raffaeu
Raffaeu

Reputation: 6973

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?

Upvotes: 8

Views: 3718

Answers (1)

Pero P.
Pero P.

Reputation: 26992

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));

Upvotes: 13

Related Questions