如何在Startup.cs中使用通用类型注册接口 [英] How to register interface with Generic type in Startup.cs

查看:308
本文介绍了如何在Startup.cs中使用通用类型注册接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在ASP.NET Core中使用WebAPI。

I am using WebAPI in ASP.NET Core.

这有效:

services.AddScoped<IApiKeysService, APIKeysService>();

现在接口返回的是通用类型T,这不会

Now that the interface is returning a generic type T This does not

services.AddScoped<IApiKeysService>();

错误使用泛型类型blah需要一种类型的参数

Error Using the generic type blah requires 1 type Arguments

或者这

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

我收到以下编译错误


类型或名称空间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.


推荐答案

接口



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

Interfaces

You cannot instantiate an interface, so it is not possible to register an interface without an implementation type (whether generic or not).

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

However, it is possible to register types as the concrete type instead of an interface.

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

在构造函数中将其指定为:

Which is specified in the constructor as:

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



开放泛型



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

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

如果有多个打开的通用参数,则需要指定使用逗号的数量。例如,使用2个开放的通用参数:

If there are multiple open generic parameters, you would specify how many using commas. For example, with 2 open generic parameters:

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

这篇关于如何在Startup.cs中使用通用类型注册接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆