IServiceProvider.GetRequiredService()和 IServiceProvider.GetService()有什么不同?
IServiceProvider.GetRequiredService()
IServiceProvider.GetService()
什么时候使用 GetRequiredService()是一个更好的主意?
GetRequiredService()
The difference is that GetService<T>() returns null if it can't find the service. GetRequiredService<T>() throws an InvalidOperationException instead.
GetService<T>()
null
GetRequiredService<T>()
InvalidOperationException
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.
GetRequiredService
GetService on the other side is for optional dependencies, which will just return null when there is no such service registered.
GetService