【问题标题】:Unable to resolve base class service无法解析基类服务
【发布时间】:2019-05-22 08:10:15
【问题描述】:

当尝试激活 Controller 时,由于服务未正确注入,我收到以下错误:

System.InvalidOperationException: '无法解析服务类型 尝试激活时出现“AnubisServer.Server.IDroneOperations” 'AnubisServer.DroneController'。'

我有以下层次结构:

public interface IOperations { }
public interface ICatalog : IOperations { }
public interface IAdmin : ICatalog { }
public interface ICatalogService : IAdmin, ISomethingElse { }

在我的初创公司中,我正在为最衍生的接口ICatalogService 提供具体实现:

启动

public void ConfigureServices(IServiceCollection services) {
    services.AddMvc();
    ICatalogService catalogService = new SomeConcreteService();
    services.AddSingleton(catalogService);
}

控制器

public class CatalogController:Controller
{
    private IOperations operations;
    public CatalogController(IOperations ops)
    {
        this.operations=ops;
    }
}

所以我不明白为什么注入基类接口不起作用,因为我提供了派生的具体实例。

有什么想法吗?

【问题讨论】:

  • 试试services.AddSingleton<IOperations>(catalogService)

标签: c# asp.net-core dependency-injection


【解决方案1】:

IServiceCollection 中的注册是键值对,其中服务(或抽象)是 ,组件(或实现)是值。将根据该确切键进行查找。所以在你的情况下,你注册了ICatalogService没有IOperations。这意味着无法解析IOperations。您必须明确注册IOperations。例如:

services.AddSingleton<IOperations>(catalogService);

【讨论】:

  • 嗯,大多数框架确实提供了类似AsImplementedInterfaces()(在 AutoFac 中)的内容,因此可以正确解决相关问题。
  • @haim770:你说得对,但我认为这里的核心问题是 OP 对 DI 容器如何工作的理解(通过基本的键值对字典查找)。
猜你喜欢
  • 1970-01-01
  • 2020-08-16
  • 2022-01-10
  • 2020-03-13
  • 2019-02-10
  • 2019-04-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多