映射器的结果为 NULL?如何将我的 api 请求映射到 dto?

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

我正在调用一个 api,然后将该响应反序列化为一个列表,然后我尝试响应一个新列表:

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

我没有使用自动映射器,而是使用了这个通用方法:

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

我收到的错误是

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

我不确定为什么它会是 null,我在这里创建了一个映射 class 应该可以处理这个问题?

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

}

_mapper 变量为空,如错误所述。 DI 你的映射器接口到你的控制器:

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.
}

为了使依赖注入起作用,您需要在 Startup.cs 中注册您的接口和实现:

public void ConfigureServices(IServiceCollection services)
{
    services.AddScoped<
        IMapToNew<Road, RoadDto>,
        RoadToRoadDtoMapper>();
}