比较 所属
GetService()is the only method onIServiceProvider, the central interface in the ASP.NET Core DI abstractions.- Third-party containers can also implement an optional interface
ISupportRequiredServicewhich provides theGetRequiredService()method.
比较 用法
- These methods behave the same when a requested
serviceTypeis available. - If the service is not available (i.e. it wasn't registered):
GetService()returnsnull- whereas
GetRequiredService()throws anInvalidOperationException.
优势 和 推荐
- The main benefit of
GetRequiredService()overGetService()is that it allows third-party containers to provide additional diagnostic information when a requested service is not available.
For that reason, it's always best to use
GetRequiredService()when using a third-party container. Personally, I will use it everywhere, even if I'm only using the built-in DI container.