Ric*_*ard 0 c# dependency-injection .net-core
与IServiceCollection.AddTransient方法相关的问题.
下面两行代码基本上做同样的事情吗?他们不一样吗?使用另一个经文是否有优势?
services.AddTransient<MyService,MyService>();
services.AddTransient<MyService>();
Run Code Online (Sandbox Code Playgroud)
我最初的代码设置在第一行,一切正常.但后来我正在调查另一个问题,我看到了第二行的例子.所以,我出于好奇而改变了我的代码,一切仍然有效.
只是好奇.
来自:
public static IServiceCollection AddTransient<TService>(this IServiceCollection services) where TService : class
{
if (services == null)
throw new ArgumentNullException(nameof (services));
return services.AddTransient(typeof (TService));
}
Run Code Online (Sandbox Code Playgroud)
call services.AddTransient(typeof(TService))
那是:
public static IServiceCollection AddTransient(this IServiceCollection services, Type serviceType)
{
if (services == null)
throw new ArgumentNullException(nameof (services));
if (serviceType == (Type) null)
throw new ArgumentNullException(nameof (serviceType));
return services.AddTransient(serviceType, serviceType);
}
Run Code Online (Sandbox Code Playgroud)
这与使用2个参数的方法完全相同:
public static IServiceCollection AddTransient<TService, TImplementation>(this IServiceCollection services) where TService : class where TImplementation : class, TService
{
if (services == null)
throw new ArgumentNullException(nameof (services));
return services.AddTransient(typeof (TService), typeof (TImplementation));
}
Run Code Online (Sandbox Code Playgroud)
因此,当您希望将寄存器实现为self时,这只是一种快捷方式.通常,您将使用不同类型的服务和实现(接口和实现或抽象类和派生类与实现).
| 归档时间: |
|
| 查看次数: |
326 次 |
| 最近记录: |