Richard
Richard

Reputation: 1106

AddTransient: Is there a difference?

Question(s) related to the IServiceCollection.AddTransient method.

Do the below 2 lines of code basically do the same thing? Are they different? Is there an advantage to using one verses the other?

services.AddTransient<MyService,MyService>();
services.AddTransient<MyService>();

I originally had my code set up with the first line and everything worked. But then I was investigating another issue and I saw an example of the second line. So, I changed my code out of curiosity and everything still worked.

Just curious.

Upvotes: 0

Views: 630

Answers (1)

Alex Lyalka
Alex Lyalka

Reputation: 1641

From sources:

public static IServiceCollection AddTransient<TService>(this IServiceCollection services) where TService : class
{
  if (services == null)
    throw new ArgumentNullException(nameof (services));
  return services.AddTransient(typeof (TService));
}

call services.AddTransient(typeof (TService))

that is:

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);
}

which is exactly the same call that method with 2 arguments do:

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));
}

So this is just shortcut for case when you want register implementation to self. Usually you will use different types for service and implementation (interface and implementation or abstract class and derived class with implementation).

Upvotes: 6

Related Questions