ASP.NET Core Interview Question #54
What is IServiceProvider?
Dependency Injection & Services Junior Beginner
Quick Interview Answer
IServiceProvider is the runtime service resolver built from the registrations in IServiceCollection. ASP.NET Core uses it internally to create objects and satisfy their registered dependencies.
Detailed Explanation
IServiceProvider is the runtime service resolver built from the registrations in IServiceCollection. ASP.NET Core uses it internally to create objects and satisfy their registered dependencies.
Application code should normally use constructor injection rather than repeatedly calling GetService() or GetRequiredService(). Manual service resolution is appropriate in limited infrastructure scenarios, such as creating a scope during startup or resolving scoped services inside a singleton-owned operation.
GetRequiredService<T>() throws if the service is unavailable, while GetService<T>() can return null.
Code Example
using var scope = app.Services.CreateScope();
var db = scope.ServiceProvider
.GetRequiredService<AppDbContext>();