119

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

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

Chris Marisic
  • 32,487
  • 24
  • 164
  • 258
Art Base
  • 1,739
  • 3
  • 15
  • 23

2 Answers2

140

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.

Tseng
  • 61,549
  • 15
  • 193
  • 205
  • 2
    You should note that if you are using an external DI provider, this semantics can change a little, for example, in StructureMap both functions behave different: https://github.com/structuremap/StructureMap.Microsoft.DependencyInjection/issues/37 – rekiem87 Feb 27 '18 at 21:52
77

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

tchelidze
  • 8,050
  • 1
  • 29
  • 49