What does GetService<T>() return compared to GetRequiredService<T>() when a service isn't registered?
Short answer
GetService () returns null if the requested service type isn't registered in the container, requiring the caller to handle the null case explicitly.
Advertisement
AModel answer
GetService<T>() returns null if the requested service type isn't registered in the container, requiring the caller to handle the null case explicitly. GetRequiredService<T>() instead throws an InvalidOperationException immediately with a clear message identifying the missing service, which is 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 == null) { /* handle missing case */ }
var requiredLogger = serviceProvider.GetRequiredService<ILogger<MyClass>>(); // throws clearly if missingReal-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