一般的依賴注入寫法如下, 角括號第一個值通常是介面, 第二個值是實作該介面的類別
services.AddScoped<ISample, Sample>();
但也有設計沒那麼好的, 角括號裡兩個都是放同一個類別
services.AddScoped<Sample, Sample>();
而我的問題是, 下面這種寫法, 角括號裡只有一個類別, 它的意義跟上面的寫法(兩個都放同一個類別)是一樣的嗎?
services.AddScoped< Sample >();
我個人測試, 它們結果是一樣的, 所以這裡< Sample >只是<Sample, Sample>的簡寫而已嗎? 謝謝
我個人測試, 它們結果是一樣的, 所以這裡< Sample >只是<Sample, Sample>的簡寫而已嗎? 謝謝
廣義來說結果是一樣的,詳細資訊可以看原始碼
下面是三個問題核心的 Method 實作
public static IServiceCollection AddScoped<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TService>(this IServiceCollection services)
where TService : class
{
ThrowHelper.ThrowIfNull(services);
return services.AddScoped(typeof(TService));
}
public static IServiceCollection AddScoped(
this IServiceCollection services,
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type serviceType)
{
ThrowHelper.ThrowIfNull(services);
ThrowHelper.ThrowIfNull(serviceType);
return services.AddScoped(serviceType, serviceType);
}
public static IServiceCollection AddScoped<TService, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TImplementation>(this IServiceCollection services)
where TService : class
where TImplementation : class, TService
{
ThrowHelper.ThrowIfNull(services);
return services.AddScoped(typeof(TService), typeof(TImplementation));
}