1

I am following Pluralsight to learn Web API concepts. I'm trying to map Book entity to the Book DTO object which is defined inside Models folder. But, I am getting below error.

I'm getting error like:

An object reference is required for the non-static field, method, or property 'Mapper.Map(object)'

I could not get much help from google as well. When googled for the same, I found two similar questions here, and here. There, I felt sense but I am not understanding how to apply the same rule in my case.

Can anyone please help me to resolve the issue!

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
Ashok kumar
  • 1,593
  • 4
  • 33
  • 68

1 Answers1

0

Followed Lucian Bargaoanu suggestion and arrived to below solution.

Write the below code in ConfigureServices method:

services.AddAutoMapper(typeof(Startup));

Introduced constructor dependency, and used IMapper functionality like below:

public class BookResultFilterAttribute : ResultFilterAttribute
{
    private readonly IMapper _mapper;
    public BookResultFilterAttribute(IMapper mapper)
    {
        _mapper = mapper;
    }
    public async override Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next)
    {
        var resultFromAction = context.Result as ObjectResult;
        if(resultFromAction?.Value == null
            || resultFromAction.StatusCode < 200
            || resultFromAction.StatusCode >= 300)
        {
            await next();
            return;
        }
        resultFromAction.Value =  _mapper.Map<Models.Book>(resultFromAction.Value);
        await next();
    }
}
Ashok kumar
  • 1,593
  • 4
  • 33
  • 68