c# 编译器不通过约束解析泛型类型参数

c# compiler doesn't resolve generic type parameters by constraints

我有以下用例:

我在 ASP.NET Core WebAPI 项目中创建了通用端点结构。

现在我想写一个 ServiceCollection 的扩展方法来轻松地将我的 Endpoint 注册到 DI。

现在我将尝试演示我想要的东西。 假设我们有:

interface IEndPoint<TInput, TOutput>
{
    TOutput Execute(TInput input);
}

class StrToIntEndPoint : IEndPoint<string, int>
{
    public int Execute(string input)
    {
        return int.Parse(input);
    }
}

class ServiceCollection { }

static class ServiceCollectionServiceExtensions
{
    public static void AddScoped<TService, TImplementation>(this ServiceCollection services) where TImplementation : TService
    {

    }
}

static class MyCustomExt
{
    // Here, I have to add TInput, TOutput type parameters to AddEndpoint method too.
    public static void AddEndpoint<T, TInput, TOutput>(this ServiceCollection services) where T: IEndPoint<TInput, TOutput>
    {
        services.AddScoped<IEndPoint<TInput, TOutput>, T>();
    }
}

class Program
{
    static void Main()
    {
        var services = new ServiceCollection();

        // Compile Error: Incorrect number of type parameters
        services.AddEndpoint<StrToIntEndPoint>();

        // fine
        services.AddEndpoint<StrToIntEndPoint, string, int>();

    }
}

我的问题是为什么编译器不通过引用 StrToIntEndPoint?

stringint 解析为 AddEndpoint 的类型参数

遗憾的是,这不是通用 constraints/arguments 的工作方式。您可以指定 NO 泛型类型参数并且编译器推断所有参数,或者您指定所有参数。

我最终为我的案例找到了以下解决方案:

static class MyCustomExt
{
    public static IServiceCollection AddScopedWitInterfaces<T>(this IServiceCollection services)
    {
        Type type = typeof(T);

        Type[] interfaces = type.GetInterfaces();

        foreach (Type interfaceType in interfaces)
        {
            services.AddScoped(interfaceType, type);
        }

        return services;
    }
}

并在 ConfigureServices 中注册我的服务:

services.AddScopedWitInterfaces<StrToIntEndpoint>();