Unable to resolve service for type ‘IRepository’ while attempting to activate ‘Controller’

huangapple go评论58阅读模式
英文:

Unable to resolve service for type 'IRepository' while attempting to activate 'Controller'

问题

我一直在尝试按照Pluralsight上的教程进行操作。但是我无法完成第一步,因为我使用的示例项目出现了以下错误:

在尝试激活'CrestSSODemo.API.Controllers.ImagesController'时,无法解析类型为'CrestSSODemo.API.Services.IGalleryRepository'的服务。

我查看了一些与此错误代码相关的Stack Overflow论坛,但我找不到一个可以帮助我的答案。我看到很多关于检查Program.cs文件是否需要将IRepository设置为scoped(AddScoped),或者检查我的Controller构造函数是否在参数中包含" I "的Repository接口的内容。我已经进行了这些检查,但找不到错误。

我有一个"API"项目,其中包含我的"Services"文件夹,其中包含"IGalleryRepository"接口和"GalleryRepository"实现。然后在同一项目的Controllers文件夹中的ImageController中,我无法解析GalleryRepository服务。我已经在API Program.cs文件中将Repositories设置为scoped,并且在ImagesController.cs中使用了正确的"using"。

以下是我的代码:

Program.cs

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

var builder = WebApplication.CreateBuilder(args);

// 将服务添加到容器中。

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

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

// 注册仓储
builder.Services.AddScoped<IGalleryRepository, GalleryRepository>();

// 注册与AutoMapper相关的服务
builder.Services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());

var app = builder.Build();

// 配置HTTP请求管道。

app.UseHttpsRedirection();

app.UseStaticFiles();

app.UseAuthorization();

app.MapControllers();

app.Run();

ImageController.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()
        {
            // 从仓储中获取
            var imagesFromRepo = await _galleryRepository.GetImagesAsync();

            // 映射到模型
            var imagesToReturn = _mapper.Map<IEnumerable<Image>>(imagesFromRepo);

            // 返回结果
            return Ok(imagesToReturn);
        }
    }
}

Edit: 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)
        {
            // 这个实现中没有代码
        }

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

            // 注意:在实际场景中,图像本身可能需要从磁盘中删除。
            // 我们在此演示场景中不执行此操作,以便更容易测试/重新运行代码。
        }

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

如果需要更多信息/代码,请告诉我,我会将其添加到问题中。

提前感谢您的帮助!

英文:

I have been trying to follow a tutorial on Pluralsight. I can't get past the first step because the example project I am using is getting the following error:

Unable to resolve service for type &#39;CrestSSODemo.API.Services.IGalleryRepository&#39; while attempting to activate &#39;CrestSSODemo.API.Controllers.ImagesController&#39;.

I have looked through a fair few Stack Overflow forums that come up when I search this error code, but I can't find one that helps. I see a lot about checking that the Program.cs file needs the IRepository to be scoped (AddScoped), or to check that my Controller constructor has the "I" on the Repository interface in the parameters. I have done these checks and cannot find what I am doing wrong.

I have an "API" project which contains my "Services" folder which contains the "IGalleryRepository" interface and the "GalleryRepository" implementation. Then in the ImageController, in the Controllers folder of the same project, I can't resolve the GalleryRepository services. I have the Repositories scoped in the API Program.cs file, and the correct "using" in the ImagesController.cs.

Here is my code:

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 =&gt; configure.JsonSerializerOptions.PropertyNamingPolicy = null);

builder.Services.AddDbContext&lt;CrestGalleryContext&gt;(options =&gt;
{
    options.UseSqlite(
        builder.Configuration[&quot;ConnectionStrings:ConnectionString&quot;]);
});

// register the repository
builder.Services.AddScoped&lt;IGalleryRepository, GalleryRepository&gt;();

// 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();

ImageController.cs

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

namespace CrestSSODemo.API.Controllers
{
    [Route(&quot;api/images&quot;)]
    [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&lt;ActionResult&lt;IEnumerable&lt;Image&gt;&gt;&gt; GetImages()
        {
            // get from repo
            var imagesFromRepo = await _galleryRepository.GetImagesAsync();

            // map to model
            var imagesToReturn = _mapper.Map&lt;IEnumerable&lt;Image&gt;&gt;(imagesFromRepo);

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

Edit: 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&lt;bool&gt; ImageExistsAsync(Guid id)
        {
            return await _context.Images.AnyAsync(i =&gt; i.Id == id);
        }

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

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

        public async Task&lt;bool&gt; IsImageOwnerAsync(Guid id, string ownerId)
        {
            return await _context.Images
                .AnyAsync(i =&gt; i.Id == id &amp;&amp; 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&#39;t do this in this demo
            // scenario to allow for easier testing / re-running the code
        }

        public async Task&lt;bool&gt; SaveChangesAsync()
        {
            return (await _context.SaveChangesAsync() &gt;= 0);
        }
    }
}

Any help would be greatly appreciated, if you need more information/code please let me know and I will add it to the question as an edit.

Thanks in advance!

答案1

得分: 0

问题原来是在客户端项目的appsettings.json中,API根URL的端口号写错了。因此,它无法找到API,也无法解析接口。我不得不更改端口号/URL(我当时使用的是localhost),以匹配API项目appsettings.json中的ApplicationUrl设置。

英文:

Turns out the problem was that the port number was wrong in the URL of the API root in the Client project appsettings.json. Therefore, it couldn't find the API, therefore could not resolve the interface. I had to change the port number/URL (I was using localhost) to match the one setup in the API project appsettings.json under ApplicationUrl.

huangapple
  • 本文由 发表于 2023年6月26日 01:28:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/76551652.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定