Advertisement
Intermediate ASP.NET Core, Dependency Injection

What does GetService<T>() return compared to GetRequiredService<T>() when a service isn't registered, and which should application code generally prefer?

Short answer

GetService () returns null if the requested service type isn't registered, requiring the caller to handle the null case explicitly.

Save ASP.NET Core mock interview
Advertisement
AModel answer
GetService<T>() returns null if the requested service type isn't registered, requiring the caller to handle the null case explicitly. GetRequiredService<T>() instead throws an InvalidOperationException immediately with a clear message identifying the missing service, generally preferred in application code since a missing required dependency usually indicates a configuration bug that should fail loudly and immediately rather than propagate a confusing null reference later.
var logger = serviceProvider.GetService<ILogger<MyClass>>();  // returns null if not registered
if (logger is null) { /* handle missing case explicitly */ }

var requiredLogger = serviceProvider.GetRequiredService<ILogger<MyClass>>();  // throws clearly if missing
Real-world example
A team standardizes on GetRequiredService throughout their startup code specifically so a missing service registration causes an immediate, clear startup failure instead of a null reference exception deep inside unrelated business logic hours later.
Likely follow-ups
  • When is GetService's null-returning behavior actually useful over GetRequiredService?
  • How does constructor injection avoid needing either of these calls directly?
Related topics