非泛型方法 'IServiceProvider.GetService(Type)' 不能与类型参数一起使用

The non-generic method 'IServiceProvider.GetService(Type)' cannot be used with type arguments

我正在使用 .NET Core 依赖项注入,但是当我尝试在另一个 class 中获取服务时,我收到 'IServiceProvider.GetService(Type)' cannot be used with type arguments 错误。

这个错误是什么意思? 我知道泛型类型参数是这样的:GenericInterface<>,而 GetService 方法不将 GenericInterface<> 作为参数。

为什么会出现此错误,我该如何解决?

界面

public interface IService
{
   void Process();
}

实现接口的class

public class Service : BaseService<IConfig, SomType>
{
    public Service(
        ILogger logger : base(logger)
    {
    }

    ...
}

BaseService class 是一个抽象 class,它实现了 IService 接口。

public abstract class BaseService<TConfig, TE> : AnotherBaseService, IService where TConfig : IConfig where TE : struct, IConvertible
{
      protected BaseService(ILogger logger): base(logger)
      {
      } 

      ...
}

AnotherBaseService

public abstract class BaseService
{
   protected readonly ILogger Logger;

   protected BaseService(ILogger logger)
   {
      Logger = logger;
   }

   ...
}

我是怎么注册的。

serviceCollection.AddScoped<IService, Service>();

我如何获得所需的服务。

var incoming = serviceProvider.GetService<IService>();

注意:我刚刚开始使用依赖注入、.NET Core,还不完全了解 DI。你的回答会很有帮助。

这意味着您的编译器只知道采用类型的方法。

你可以打电话给

var incoming = serviceProvider.GetService(typeof(IService));

或者您可以添加

using Microsoft.Extensions.DependencyInjection;

确保您的编译器知道允许您将类型指定为泛型参数的扩展方法。这可能需要安装软件包 Microsoft.Extensions.DependencyInjection.Abstractions

通用GetService< T>方法是一种扩展方法。这意味着您需要一个 :

using Microsoft.Extensions.DependencyInjection;

让编译器找到它。

此方法仅适用于可选 服务。如果无法构造对象,它将 return null ,要么是因为类型未注册,要么是因为它的某些依赖项丢失。

GetRequiredService 应在应用程序无法运行时使用,除非服务可用。如果无法创建实例,则会抛出 InvalidOperationException。

当抛出该异常时,完整的异常文本将巨大帮助找到实际问题。构造函数中抛出的异常可以出现在 Exception.InnerException property. The sequence of calls that ended up in an exception being thrown will appear in the StackTrace property. Calling Exception.ToString() 将 return 一个字符串中,该字符串包含 所有 当前异常和任何内部异常的信息。

以上帖子中解释得很好的简短答案:

ServiceProvider.GetService<T>(); 

使用以下需要明确定义的命名空间而不是依赖智能感知

using Microsoft.Extensions.DependencyInjection;

另请注意,如果在此之后出现空异常,可能会出现多个问题:

  1. 在启动时确保将 Hostbuilder 服务设置为 ServiceProvider 值

    服务提供商=host.Services;

  2. 其他可能是 T 的构造函数 class 无法解析正在使用的接口的依赖性。

**

Thanks ! Happy Coding :)

**