gpt4 book ai didi

c# - 尝试激活 Controller 类时未解析接口(interface) (IOwnerRepository)

转载 作者:行者123 更新时间:2023-11-30 23:08:57 25 4
gpt4 key购买 nike

我有一个如下所示的接口(interface):这个接口(interface)是我的 GetAllOwners 方法签名。

namespace Pms.Core
{
public interface IOwnerRepository
{
Task<IEnumerable<Owner>> GetAllOwners();
}
}

驱动此接口(interface)的我的 Repository 类如下所示。此类应返回数据库中的所有所有者。

namespace Pms.Persistence
{
public class OwnerRepository : IOwnerRepository
{
private readonly PmsDbContext context;
public OwnerRepository(PmsDbContext context)
{
this.context = context;
}

public async Task<IEnumerable<Owner>> GetAllOwners()
{
return await context.Owners.ToListAsync();
}
}
}

我有一个 Controller 类,它使用 Repository 类来显示所有所有者。

namespace Pms.Controllers
{
[Route("/api/owners")]
public class OwnersController : Controller
{
private readonly PmsDbContext context;
private readonly IMapper mapper;
private readonly IOwnerRepository repository;

public OwnersController(PmsDbContext context, IMapper mapper,
IOwnerRepository repository)
{
this.repository = repository;
this.context = context;
this.mapper = mapper;
}

[HttpGet]
public async Task<IEnumerable<OwnerResource>> GetOwners()
{
var owners = await repository.GetAllOwners();
return mapper.Map<IEnumerable<Owner>,
IEnumerable<OwnerResource>>(owners);
}
}
}

最后,这是我注册服务的代码片段。

services.AddScoped<IOwnerRepository, OwnerRepository>();

当我测试此 API 时,我得到“处理请求时发生未处理的异常。InvalidOperationException:在尝试激活“Pms.Controllers.OwnersController”时无法解析类型“Pms.Core.IOwnerRepository”的服务.

我所做的是确保 API 在没有接口(interface)的情况下也能正常工作。这个应用程序在不使用接口(interface)的情况下工作得很好,但不知何故我无法实现接口(interface)来使我的应用程序更健壮和面向对象。

最佳答案

我找到了罪犯。依赖注入(inject)的版本不兼容。我使用的是 2.0,所以我降级到 1.2.0,一切正常。

<PackageReference
Include="AutoMapper.Extensions.Microsoft.DependencyInjection" Version="1.2.0" />

关于c# - 尝试激活 Controller 类时未解析接口(interface) (IOwnerRepository),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46181896/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com