我在 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/