Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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()?

like image 584
Art Base Avatar asked Aug 09 '17 09:08

Art Base


People also ask

What is the difference between GetService and 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.

What is IServiceProvider in asp net core?

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.

What is IServiceCollection in .NET core?

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.

What is IServiceScopeFactory?

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) .


2 Answers

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.

like image 64
Tseng Avatar answered Oct 13 '22 12:10

Tseng


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

like image 66
tchelidze Avatar answered Oct 13 '22 11:10

tchelidze