Search code examples
c#.netdependency-injectiontypeofscoped

What is the difference with dependency injection when using typeof?


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


Solution

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