C# 在Startup.cs中添加服务时,有关ASP.NET核心中的C模式的问题

C# 在Startup.cs中添加服务时,有关ASP.NET核心中的C模式的问题,c#,generics,design-patterns,generic-function,C#,Generics,Design Patterns,Generic Function,关于配置服务的此代码: public void ConfigureServices(IServiceCollection services) { services.AddSingleton<IDb, Db>(); services.AddControllers(); } 从语义上讲,两者的意思相同。但是,使用泛型方法的一个优点是,可以在编译时强制对传递给方法调用的类型施加约束 在中,请注意约束,其中TImplementation:class,TService。编译器

关于配置服务的此代码:

public void ConfigureServices(IServiceCollection services)
{
    services.AddSingleton<IDb, Db>();
    services.AddControllers();
}

从语义上讲,两者的意思相同。但是,使用泛型方法的一个优点是,可以在编译时强制对传递给方法调用的类型施加约束

在中,请注意约束,其中TImplementation:class,TService。编译器可以在编译时检查Db类型是否实现了IDb并且是一个类


对于非泛型方法,这在编译时是不可能的。相反,可以在运行时检查它,并抛出运行时错误。

从语义上讲,两者的意思相同。但是,使用泛型方法的一个优点是,可以在编译时强制对传递给方法调用的类型施加约束

在中,请注意约束,其中TImplementation:class,TService。编译器可以在编译时检查Db类型是否实现了IDb并且是一个类


对于非泛型方法,这在编译时是不可能的。相反,可以在运行时检查它,并抛出运行时错误。

如果搜索Microsoft文档,您会发现所有Addsingleton的工作原理相同,唯一不同的是条目:

AddSingleton:将TService中指定类型的singleton服务以及TImplementation中指定的实现类型添加到指定的IServiceCollection

AddSingletonIServiceCollection,Type,Type:将serviceType中指定类型的singleton服务以及implementationType中指定类型的实现添加到指定的IServiceCollection


如果搜索Microsoft的文档,您会发现所有Addsingleton的工作原理相同,唯一不同的是条目:

AddSingleton:将TService中指定类型的singleton服务以及TImplementation中指定的实现类型添加到指定的IServiceCollection

AddSingletonIServiceCollection,Type,Type:将serviceType中指定类型的singleton服务以及implementationType中指定类型的实现添加到指定的IServiceCollection

AddSingleton的实现如下所示:

public static IServiceCollection AddSingleton<TService, TImplementation>(this IServiceCollection services)
    where TService : class
    where TImplementation : class, TService
{
    if (services == null)
    {
        throw new ArgumentNullException(nameof(services));
    }

    return services.AddSingleton(typeof(TService), typeof(TImplementation));
}
where TService : class
where TImplementation : class, TService
除了这两种类型都必须是引用类型之外,还有一个额外的要求,即TImplementation继承自TService。这确保您可以在需要TService的地方实际使用TImplementation类型的实例。这也是该计划背后的想法。通过使用类型约束,此检查将在编译时验证,因此您可以确保这将在运行时起作用,因为如果使用其他重载,则无法保证这一点

不用说,AddTransient和AddScope在各自的非泛型重载上以相同的方式工作。

AddSingleton的实现如下所示:

public static IServiceCollection AddSingleton<TService, TImplementation>(this IServiceCollection services)
    where TService : class
    where TImplementation : class, TService
{
    if (services == null)
    {
        throw new ArgumentNullException(nameof(services));
    }

    return services.AddSingleton(typeof(TService), typeof(TImplementation));
}
where TService : class
where TImplementation : class, TService
除了这两种类型都必须是引用类型之外,还有一个额外的要求,即TImplementation继承自TService。这确保您可以在需要TService的地方实际使用TImplementation类型的实例。这也是该计划背后的想法。通过使用类型约束,此检查将在编译时验证,因此您可以确保这将在运行时起作用,因为如果使用其他重载,则无法保证这一点


不用说,AddTransient和AddScope在各自的非泛型重载上以相同的方式工作。

如果Db表示与数据库相关的任何内容,那么将其作为单例可能是一个重大错误。正如你所问的,不,两者的意思都一样。@WiktorZychla,谢谢。是的,我使用了代码片段示例中的AddSingleton,而不是实际应用程序。如果Db表示与数据库相关的任何内容,那么将其作为singleton可能是一个重大错误。正如你所问的,不,两者的意思都一样。@WiktorZychla,谢谢。是的,我使用了代码片段示例中的AddSingleton,而不是实际应用程序。