2

I was investigating a connection issue and came across the code. I tried to research the difference but could not find any clear answer to the question.

The main issue we faced was connections not closing for the service bus when using Azure's service bus package. But this looked more like it was not disposed of correctly.

When using dependency injection for adding scoped services, typeof was used.

The first scenario is:
services.AddScoped(typeof(IServiceBusMessageSender), typeof(ServiceBusMessageSender));

Does using typeof do anything different from the 2nd scenario?

The second scenario is:
services.AddScoped<IServiceBusMessageSender, ServiceBusMessageSender>();

Willem
  • 73
  • 8
  • 1
    The main difference between the two approaches is that the generic version is shorter and easier to read, but the non-generic version gives you more flexibility if you need to specify the types at runtime. – N0m4n904 Jan 04 '23 at 09:28
  • 3
    Here is the [code for that metthod](https://github.com/dotnet/runtime/blob/main/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/ServiceCollectionServiceExtensions.cs#L210). I'm not entirely sure what you're trying to say with your question. It sounds like you're saying that you changed from using `typeof` to using generics and that solved your problem. That isn't really possible since the generic method just calls the non-generic method. There must be something else at play here. – ProgrammingLlama Jan 04 '23 at 09:28
  • 2
    I would imagine that the lowered code is even the exact same. – Fildor Jan 04 '23 at 09:36

1 Answers1

3

The second one will call the first one. If you check the source code you can find

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

You can find source code here

Here is the first one implemention

public static IServiceCollection AddScoped(
    this IServiceCollection services,
    Type serviceType,
    [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType)
{
    ThrowHelper.ThrowIfNull(services);
    ThrowHelper.ThrowIfNull(serviceType);
    ThrowHelper.ThrowIfNull(implementationType);

    return Add(services, serviceType, implementationType, ServiceLifetime.Scoped);
}
MichaelMao
  • 2,596
  • 2
  • 23
  • 54