On IServiceProvider what are the differences between the GetRequiredService and GetService methods?

Dependency Injectionasp.net Core.Net Core

Dependency Injection Problem Overview


What are the differences between IServiceProvider.GetRequiredService() and IServiceProvider.GetService()?

When is it a better idea to use GetRequiredService()?

Dependency Injection Solutions


Solution 1 - Dependency Injection

You should rarely have to call these methods at all, as you should use constructor injection where ever possible.

In rare cases, such as factories or to dynamically instantiate command handlers, you can resolve it yourself.

That being said, you should use GetRequiredService where you require the service. It will throw an exception, when the service is not registered.

GetService on the other side is for optional dependencies, which will just return null when there is no such service registered.

Solution 2 - Dependency Injection

The difference is that GetService<T>() returns null if it can't find the service. GetRequiredService<T>() throws an InvalidOperationException instead.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionArt BaseView Question on Stackoverflow
Solution 1 - Dependency InjectionTsengView Answer on Stackoverflow
Solution 2 - Dependency InjectiontchelidzeView Answer on Stackoverflow