Does the order of method invocations matter in Startup.ConfigureServices?

Viewed 1094

Does the order of .AddXxxxxxx method invocations matter in Startup.ConfigureServices?

public void ConfigureServices(IServiceCollection services)
{
    services.AddTransient<IWorkService, WorkService>();

    services.AddHostedService<QueuedBackgroundService>(); 
    services.AddTransient<IQueuedBackgroundService, QueuedBackgroundService>();

    services.AddTransient<IJobService, JobService>();

    services.AddControllers();
}
1 Answers

Adding services to the service collection is not order dependent by default (Does not include 3rd Party integration frameworks that interact with the service collection).

In the case of registering multiple of the same abstraction, subsequent calls to .AddXxxxxxx overrides the previous one when resolved as the abstraction and adds to the previous one when multiple services are resolved via IEnumerable<IMyType>. Services appear in the order they were registered when resolved via IEnumerable<{SERVICE}>.

Reference: Service registration methods

You are basically adding a set of instructions to the collection.

When the provider is being built, the framework will inspect the collection for what is needed so the provider knows how to handle requests for services to be resolved.

Related