Updated on

We get an IServiceProvider from app.Services once the app is built, from a constructor parameter, from HttpContext.RequestServices inside a request, or from BuildServiceProvider() on a ServiceCollection we create ourselves.

It sits at the center of .NET’s dependency injection system and works as a service locator: we ask it for a type, and it hands us an instance.

To download the source code for this article, you can visit our GitHub repository.

Which one we reach for depends on where our code runs, and two of them come with traps.

What Is IServiceProvider?

IServiceProvider is the interface .NET uses to hand out services. It lives in the System namespace and has one method, GetService(Type), which returns the registered instance, or null when nothing is registered for that type.

In an ASP.NET Core or worker app, the object behind that interface is ServiceProvider from Microsoft.Extensions.DependencyInjection. We never create it with new. The host builds it from the IServiceCollection we fill in Program.cs, and BuildServiceProvider() does the same for a collection of our own.

The provider also tracks lifetimes. Singletons come from the root provider. Transient services get a new instance on every call. Scoped services come from a scope, which we open with CreateScope(), and when we dispose the scope, it disposes what it created.

Day to day, we rarely call the Type-based method. We call GetService<T>() and GetRequiredService<T>(), the generic extension methods from the ServiceProviderServiceExtensions class.

IServiceProvider is a core interface that defines a single method, GetService(). Here’s how the System namespace declares it:

public interface IServiceProvider
{    
    object? GetService(Type serviceType);
}

This method allows us to resolve instances of services registered in the DI container. It’s beneficial when we need to obtain service instances at runtime dynamically.

Where Can We Reach IServiceProvider in an Application?

For demonstration purposes, let’s create a simple interface and some services that implement it:

public interface IExampleService { }

public class ExampleService : IExampleService { }

public class DevelopmentExampleService : IExampleService { }

Next, in the Program.cs of an ASP.NET Core project, we register this service as scoped in the DI container:

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddScoped<IExampleService, ExampleService>();

Now, let’s explore how to resolve this service using IServiceProvider in different contexts.

During Application Startup

There are several ways to access IServiceProvider during the startup phase of an application.

The first one works, but we don’t want it in application code. We can call BuildServiceProvider() on builder.Services before building the application and resolve our service from the result:

var serviceProvider = builder.Services.BuildServiceProvider();
var serviceInstance1 = serviceProvider.GetService<IExampleService>();

The build flags this line straight away with analyzer warning ASP0000:

warning ASP0000: Calling 'BuildServiceProvider' from application code results in an additional copy of singleton services being created. Consider alternatives such as dependency injecting services as parameters to 'Configure'. (https://aka.ms/AA5k895)

That second provider is a separate container. It creates its own copy of every singleton not registered as a ready-made instance, so such a singleton resolved from it and the same singleton resolved from app.Services are two different objects. It has no scope either, so a scoped service resolved from it hangs around as long as that provider does.

Microsoft’s dependency injection guidelines say: “Avoid calls to BuildServiceProvider when configuring services.” The same guidance points to the fix, a registration overload that hands us the IServiceProvider. That’s the factory method:

builder.Services.AddScoped<IExampleService>(serviceProvider =>
{
    var config = serviceProvider.GetRequiredService<IHostEnvironment>();

    return config.IsDevelopment() ? new DevelopmentExampleService() : new ExampleService();
});

Here, we dynamically resolve the environment and choose the appropriate implementation of IExampleService based on its value.

Once the application is built using builder.Build(), services can be properly resolved using the app.Services property:

var app = builder.Build();

using var serviceScope = app.Services.CreateScope();
var serviceInstance2 = serviceScope.ServiceProvider.GetRequiredService<IExampleService>();

Here, we open a scope first because IExampleService is scoped. If we skip the scope and ask app.Services for it directly, the call throws an InvalidOperationException in the Development environment, where ASP.NET Core turns on scope validation. In Production, the same call succeeds with no error, and the scoped service then lives until the app shuts down.

If you want to know more about dependency injection lifetimes, check out our article Dependency Injection Lifetimes in ASP.NET Core.

Within a Service Class

In services like background tasks, injecting IServiceProvider allows dynamic resolution of scoped services:

public class ExampleBackgroundService(IServiceProvider serviceProvider) : BackgroundService
{
    protected override Task ExecuteAsync(CancellationToken stoppingToken)
    {
        using var scope = serviceProvider.CreateScope();
        var service = scope.ServiceProvider.GetRequiredService<IExampleService>();

        return Task.CompletedTask;
    }
}

Here, the IExampleService is resolved within the background service’s execution scope, ensuring proper lifetimes.

A hosted service is registered as a singleton, so it shouldn’t take a scoped service through its constructor. Opening a scope from the injected provider is how it borrows one for a unit of work, and using disposes the scope, and everything it created, when the method ends. It’s the same trick we use to inject a DbContext into an IHostedService.

CreateScope() itself is an extension method that asks the provider for IServiceScopeFactory. If a class only ever needs scopes, injecting IServiceScopeFactory gives it the same result with a narrower dependency.

Within a Controller

Using IServiceProvider in a controller is straightforward, thanks to HttpContext.RequestServices:

using Microsoft.AspNetCore.Mvc;

[ApiController]
public class ExampleController : ControllerBase
{
    [HttpGet("/api/example/get-serviceprovider-within-api-controller")]
    public IActionResult GetIServiceProviderFromHttpContext()
    {
        var resolvedService = HttpContext.RequestServices.GetService<IExampleService>();

        return Ok(resolvedService is not null);
    }
}

This approach simplifies sharing dependencies across multiple controllers without explicitly injecting them into each one when necessary.

RequestServices is the provider for the current request’s scope, so a scoped service we resolve here is the same instance for the whole request, and it’s disposed when the request ends. When only one action needs a service, the [FromServices] attribute on an action parameter gets it for us without the service locator.

Manually Building a ServiceProvider

In unit testing or console applications, we might need to manually create a ServiceProvider using the BuildServiceProvider() method, similar to our example during application startup. In a console app, we first add the Microsoft.Extensions.DependencyInjection NuGet package and keep the IExampleService types from earlier:

using Microsoft.Extensions.DependencyInjection;

var services = new ServiceCollection();
services.AddSingleton<IExampleService, ExampleService>();
var serviceProvider = services.BuildServiceProvider();
var myService = serviceProvider.GetService<IExampleService>();

This approach is particularly useful when the full ASP.NET Core infrastructure is unavailable, allowing us to control service registration and resolution manually.

Here, BuildServiceProvider() is fine, because this provider is the only one the program has. ServiceProvider is also IDisposable, and disposing it disposes the services it created at the root.

What Is the Difference Between GetService and GetRequiredService?

GetService<T>() returns null when nothing is registered for T. GetRequiredService<T>() throws an InvalidOperationException instead. The difference decides where a missing registration shows up.

With GetService<T>(), the null travels on until a later line touches it and fails with a NullReferenceException, often far from the real cause. With GetRequiredService<T>(), the failure happens on the line that asked, and the message names the missing type.

So we use GetRequiredService<T>() whenever the code can’t work without the service, which is most of the time. GetService<T>() fits an optional service with a fallback, like the controller above, which only reports whether the service is there.

Both are extension methods from Microsoft.Extensions.DependencyInjection. The interface itself only has the Type-based GetService(), which returns null the same way. It also returns an object, so serviceProvider.GetService(typeof(IExampleService)) needs a cast before we can use the result.

Let’s see both on a provider with nothing registered:

var emptyProvider = new ServiceCollection().BuildServiceProvider();

var service = emptyProvider.GetService<IExampleService>();
Console.WriteLine(service is null);
var requiredService = emptyProvider.GetRequiredService<IExampleService>();

The first call prints True, and the second one stops the program:

True
Unhandled exception. System.InvalidOperationException: No service for type 'IExampleService' has been registered.

If that message turns up in a real application, our guide to the unable to resolve service for type error walks through the usual causes.

When Should We Avoid Using IServiceProvider Directly?

Using IServiceProvider directly can bring benefits in specific scenarios such as factory patterns, middleware, or conditionally resolving services at runtime. However, we should avoid its overuse to prevent service lifetime mismatches, such as resolving scoped services from singletons, which can lead to memory leaks or unexpected behavior.

Additionally, relying too heavily on IServiceProvider complicates testing, obscures class dependencies, and can lead to tight coupling. Resolving services this way follows the service locator pattern, and Microsoft’s dependency injection guidelines put it on the list of things to avoid: “Avoid using the service locator pattern.”

A common mistake is resolving scoped services from singleton instances, which leads to improper lifecycle management and potential memory leaks. We should dispose the scopes we create, not the services we resolve from them, because the container disposes everything it creates. Transient services need care too: a disposable transient resolved from the root provider stays in memory until the provider itself is disposed, which for app.Services means app shutdown. Resolving it from a scope lets the scope clean it up.

The general rule is that we should always favor constructor injection, as the framework knows best how to manage lifetimes, dependencies, and their disposal. This approach also promotes clean, testable, and maintainable code and makes our dependencies explicit. 

Conclusion

This article explored various ways to obtain and use IServiceProvider in .NET, from application startup to within services, controllers, and more. By understanding when and how to access IServiceProvider, we can manage service lifetimes effectively and maintain clean, efficient code.

If we want the full picture of how the container itself is put together, from registration to scope validation, our article on dependency injection in ASP.NET Core is the next stop.

Tested with .NET 11 (SDK 11.0.100, runtime 11.0.0) and Microsoft.Extensions.DependencyInjection 11.0.0.