frictionlesspulley
frictionlesspulley

Reputation: 12368

Accessing Request in Automapper Custom Resolver

I am working on an ASP.NET Web API project.

I use Auto-mapper for mapping from my domain objects to DTOs

How do pass in a request parameters into a Custom ValueResolver ?

I saw a couple of similar questions on stackoverflow posted a TWO years back which mention that this cannot be done. Is this the same situation now or has this been resolved ?

Link to similar question raised a TWO years ago : How to pass values to a Custom Resolver in Automapper?

There is a ConstructedBy method which can be used to inject your own Resolver object , but I don't how to access pass in Request

Thanks

Upvotes: 1

Views: 617

Answers (1)

frictionlesspulley
frictionlesspulley

Reputation: 12368

I used the AfterMap() feature for the time being. I am hoping someone has a better solution.

For simplicity if I reduced my source and destination classes to

public class Source {

       public string Value {get;set;}

}

public class Destination{

       public string Value {get;set;}            

       private bool _reset;

       public Destination(bool reset = false){
           _reset = reset;
       } 

       public void TryReset(){
           if(!_reset) return;

            Value = string.Empty;

       }

}

I added a AfterMap() in the Mapping configuration to call the reset method.

Mapper.CreateMap<Source, Destination>()
      .AfterMap( (source, dest) => dest.TryReset());

In the controller I pass the reset flag from the Request directly as

var destination = Mapper.Map(new Source { Value ="Hello" },
                             new Destination(flag));

Upvotes: 1

Related Questions