You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

激活ImagesController时无法解析IGalleryRepository服务求助

ASP.NET Core服务注入异常:无法解析IGalleryRepository以激活ImagesController

遇到的错误信息:

Unable to resolve service for type 'CrestSSODemo.API.Services.IGalleryRepository' while attempting to activate 'CrestSSODemo.API.Controllers.ImagesController'.

我正在跟着Pluralsight的教程做API项目,第一步就卡在这里。已经查了多篇Stack Overflow帖子,试过常规排查手段:

  • 确认Program.cs里用AddScoped<IGalleryRepository, GalleryRepository>()注册了仓储服务
  • 检查ImagesController构造函数参数确实用的是带I的接口类型IGalleryRepository
  • 确认控制器里添加了正确的using CrestSSODemo.API.Services;引用

项目结构:API项目中,Services文件夹包含IGalleryRepository接口和GalleryRepository实现类,Controllers文件夹下的ImagesController依赖该仓储服务。已在Program.cs中注册作用域仓储,但仍无法解析服务。

以下是相关代码:

Program.cs

using CrestSSODemo.API.Services;
using CrestSSODemo.API.DbContexts;
using Microsoft.EntityFrameworkCore;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers()
    .AddJsonOptions(configure => configure.JsonSerializerOptions.PropertyNamingPolicy = null);

builder.Services.AddDbContext<CrestGalleryContext>(options =>
{
    options.UseSqlite(
        builder.Configuration["ConnectionStrings:ConnectionString"]);
});

// register the repository
builder.Services.AddScoped<IGalleryRepository, GalleryRepository>();

// register AutoMapper-related services
builder.Services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());

var app = builder.Build();

// Configure the HTTP request pipeline.

app.UseHttpsRedirection();

app.UseStaticFiles();

app.UseAuthorization();

app.MapControllers();

app.Run();

ImagesController.cs

using AutoMapper;
using CrestSSODemo.API.Services;
using CrestSSODemo.Model;
using Microsoft.AspNetCore.Mvc;

namespace CrestSSODemo.API.Controllers
{
    [Route("api/images")]
    [ApiController]
    public class ImagesController : ControllerBase
    {
        private readonly IGalleryRepository _galleryRepository;
        private readonly IWebHostEnvironment _hostingEnvironment;
        private readonly IMapper _mapper;

        public ImagesController(IGalleryRepository galleryRepository, IWebHostEnvironment hostingEnvironment, IMapper mapper)
        {
            _galleryRepository = galleryRepository;
            _hostingEnvironment = hostingEnvironment;
            _mapper = mapper;
        }

        [HttpGet()]
        public async Task<ActionResult<IEnumerable<Image>>> GetImages()
        {
            // get from repo
            var imagesFromRepo = await _galleryRepository.GetImagesAsync();

            // map to model
            var imagesToReturn = _mapper.Map<IEnumerable<Image>>(imagesFromRepo);

            // return
            return Ok(imagesToReturn);
        }
    }
}

补充:GalleryRepository.cs

using CrestSSODemo.API.DbContexts;
using CrestSSODemo.API.Entities;
using Microsoft.EntityFrameworkCore;

namespace CrestSSODemo.API.Services
{
    public class GalleryRepository : IGalleryRepository
    {
        private readonly CrestGalleryContext _context;

        public GalleryRepository(CrestGalleryContext galleryContext)
        {
            _context = galleryContext ??
                throw new ArgumentNullException(nameof(galleryContext));
        }

        public async Task<bool> ImageExistsAsync(Guid id)
        {
            return await _context.Images.AnyAsync(i => i.Id == id);
        }

        public async Task<Image?> GetImageAsync(Guid id)
        {
            return await _context.Images.FirstOrDefaultAsync(i => i.Id == id);
        }

        public async Task<IEnumerable<Image>> GetImagesAsync()
        {
            return await _context.Images
                .OrderBy(i => i.Title).ToListAsync();
        }

        public async Task<bool> IsImageOwnerAsync(Guid id, string ownerId)
        {
            return await _context.Images
                .AnyAsync(i => i.Id == id && i.OwnerId == ownerId);
        }

        public void AddImage(Image image)
        {
            _context.Images.Add(image);
        }

        public void UpdateImage(Image image)
        {
            // no code in this implementation
        }

        public void DeleteImage(Image image)
        {
            _context.Images.Remove(image);

            // Note: in a real-life scenario, the image itself potentially should 
            // be removed from disk.  We don't do this in this demo
            // scenario to allow for easier testing / re-running the code
        }

        public async Task<bool> SaveChangesAsync()
        {
            return (await _context.SaveChangesAsync() >= 0);
        }
    }
}

需要更多信息或代码的话可以补充,感谢帮忙排查!

内容的提问来源于stack exchange,提问作者Jack Reynolds

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 18:23:21