依赖注入 net core InvalidOperationException

Dependency injection net core InvalidOperationException

我是 AutoMapper 的新手,我正在尝试构建一个 API。启动新 API 项目 (WeatherForecast) 时出现的默认端点工作正常。但是,当我尝试到达端点 api/nationalparks 时,出现此错误:

控制器:

namespace NationalParksAPI.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class NationalParksController : Controller
    {
        private INationalParkRepository _npRepo;
        private ParkyMappings _parksMapper;

        public NationalParksController(INationalParkRepository npRepo, ParkyMappings parksMapper )
        {
            _npRepo = npRepo;
            _parksMapper = parksMapper;
        }

        public IActionResult GetNationalParks()
        {
            var objList = _npRepo.GetNationalParks();
            return Ok(objList);
        }

    }
}

映射器:

public class ParkyMappings : Profile
{
    public ParkyMappings()
    {
        CreateMap<NationalParkEntity, NationalParkDTO>().ReverseMap();
    }
}

在启动时配置服务(请注意,AddAutoMapper 方法在不使用 AutoMapper 包的情况下工作,这与我遵循的教程不同):

public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContextPool<NationalParksDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("ParksDBConnection")));
        services.AddScoped<INationalParkRepository, NationalParkRepository>();
        services.AddAutoMapper(typeof(ParkyMappings));
        services.AddControllers();
       
    }

实体:

public class NationalParkEntity
{
    [Key]
    public int Id { get; set; }
    [Required]
    public string Name { get; set; }
    [Required]
    public string state { get; set; }
    public DateTime CreatedAt { get; set; }
    public DateTime Eistablished { get; set; }
}

DTO:

    public class NationalParkDTO
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string state { get; set; }
    public DateTime CreatedAt { get; set; }
    public DateTime Eistablished { get; set; }
}

如有任何意见,我们将不胜感激。

您不应该将 ParkyMappings 作为 Controller 的依赖项。 ParkyMappings(作为Profile 子类)仅用于在应用程序启动时初始化Automapper。它在 Controller.

中没有任何意义

您应该将 IMapper mapper 传递给 Controller

namespace NationalParksAPI.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class NationalParksController : Controller
    {
        private INationalParkRepository _npRepo;
        private IMapper _mapper;

        public NationalParksController(INationalParkRepository npRepo, IMapper mapper)
        {
            _npRepo = npRepo;
            _mapper  = mapper;
        }

        public IActionResult GetNationalParks()
        {
            var objList = _npRepo.GetNationalParks();
            var entityList = _mapper.Map<NationalParkEntity[]>(objList)
            return Ok(entityList);
        }

    }
}

并且,也许,使用此注册来代替 Automapper:

services.AddAutoMapper(this.GetType().Assembly);