Result of mapper is NULL? How do I map my api request to a dto?

0

I'm making a call to an api, and then deserializing that response to a list, when i am then trying the response to a new list:

    public async Task<IEnumerable<RoadDto>> GetRoadStatusDetail()
    {
        List<Road> road = await CallApi();

        return road
            .Select(x => _mapper.Map(x)); 

    }


    private async Task<List<Road>> CallApi()
    {
        HttpClient client = new HttpClient();
        client.BaseAddress = new Uri(baseURL);

        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        HttpResponseMessage res = await client.GetAsync(baseURL);

        if (res.IsSuccessStatusCode)
        {
            var roadResponse = res.Content.ReadAsStringAsync().Result;

           var road = JsonConvert.DeserializeObject<List<Road>>(roadResponse);

           return road;
        }

        return null;
    }

I am not using auto mapper, rather I am using this generic method:

public interface IMapToNew<in TIn, out TOut>
{
    TOut Map(TIn model);
}

The error I am getting is

System.NullReferenceException
  HResult=0x80004003
  Message=Object reference not set to an instance of an object.
_mapper was null. 

I'm not sure why it would be null, i've created a mapping class here that should handle that?

   public class RoadToRoadDtoMapper : IMapToNew<Road, RoadDto>
{
    public RoadDto Map(Road model)
    {
        return new RoadDto
        {
            DisplayName = model?.DisplayName,
            StatusSeverity = model?.StatusSeverity,
            StatusSeverityDescription = model?.StatusSeverityDescription
        };
    }

}
c#
mapping
dto
asked on Stack Overflow Dec 16, 2019 by dros

1 Answer

0

The _mapper variable is null, as the error states. DI your mapper interface to your controller:

private readonly IMapToNew<Road, RoadDto> _mapper;

// Make sure your controller constructor takes your mapper interface.
public MyController(IMapToNew<Road, RoadDto> mapper)
{
    // Assign the constructor parameter to your instance 
    _mapper = mapper; variable.
}

In order for dependency injection to work, you need to register your interface and the implementation in Startup.cs:

public void ConfigureServices(IServiceCollection services)
{
    services.AddScoped<
        IMapToNew<Road, RoadDto>,
        RoadToRoadDtoMapper>();
}
answered on Stack Overflow Dec 16, 2019 by kaffekopp • edited Dec 16, 2019 by kaffekopp

User contributions licensed under CC BY-SA 3.0