What are the differences between IServiceProvider.GetRequiredService()
and IServiceProvider.GetService()
?
When is it a better idea to use GetRequiredService()
?
The difference is in their behaviour when the serviceType has not been registered: GetService - returns null if the service is not registered. GetRequiredService - throws an Exception if the service is not registered.
The IServiceProvider is responsible for resolving instances of types at runtime, as required by the application. These instances can be injected into other services resolved from the same dependency injection container. The ServiceProvider ensures that resolved services live for the expected lifetime.
AddScoped(IServiceCollection, Type, Type) Adds a scoped service of the type specified in serviceType with an implementation of the type specified in implementationType to the specified IServiceCollection.
Essentially IServiceScopeFactory is the interface responsible for creating IServiceScope instances which are in turn responsible for managing the lifetime of IServiceProvider - which is the interface we use to resolve dependencies i.e. IServiceProvider. GetService(type) .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With