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

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.


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