Art Base
Art Base

Reputation: 1879

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

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

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

Upvotes: 129

Views: 23168

Answers (2)

tchelidze
tchelidze

Reputation: 8318

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

Upvotes: 86

Tseng
Tseng

Reputation: 64150

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.

Upvotes: 150

Related Questions