c# - 如何在 Startup.cs 中使用通用类型注册接口(interface)

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

我在 ASP.NET Core 中使用 WebAPI。

这个有效:

services.AddScoped<IApiKeysService, APIKeysService>();

既然接口(interface)返回的是泛型类型 T 这不

services.AddScoped<IApiKeysService>();

错误使用泛型类型 blah 需要 1 个类型参数

或者这个

services.AddScoped<IApiKeysService<T>>();

我得到以下编译错误

type or namespace T cannot be found

如何在 Startup.cs 中注册它?

NOTE: I cannot use a concrete type because the interface member is a base class with generic method.

最佳答案

接口(interface)

您无法实例化接口(interface),因此无法注册没有实现类型(无论是否通用)的接口(interface)。

但是,可以将类型注册为具体类型而不是接口(interface)。

services.AddScoped(typeof(Foo<>));

在构造函数中指定为:

public MyService(Foo<ClosingType> foo)
{
    // implementation
}

开放泛型

开放泛型在 .NET 中总是以相同的方式指定:typeof(SomeGenericType<>) .

services.AddScoped(typeof(IFoo<>), typeof(Foo<>));

如果有多个开放通用参数,您可以使用逗号指定有多少个。例如,有 2 个开放的通用参数:

services.AddScoped(typeof(IFoo<,>), typeof(Foo<,>));

关于c# - 如何在 Startup.cs 中使用通用类型注册接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49352434/

相关文章:

c# - 将类成员的值添加到数组 C#

c# - 在 C# 应用程序中使用 LINQ to SQL 的最佳实践方法是什么? [设计模式]

c# - 如何使用反射调用泛型方法?

java - Java 中是否可以禁止泛型中的某些父类(super class)?

c# - 有没有办法在 asp.net core 3.1 Rest-API 中使用 Identity Server 功能

c# - 在 ASP.NET Core 中获取浏览器语言?

c# - 使字符串中的小写大写和大写小写

c# - 如何在 C# 中定义 TBBUTTON 结构?

javax.persistence.Query 与泛型

c# - 用自己的图标替换 Google Material 图标,保留相同的内容代码或创建新的