DI中GetService()和GetRequiredService() 的异同

405 阅读1分钟

比较 所属

  • GetService() is the only method on IServiceProvider, the central interface in the ASP.NET Core DI abstractions.
  • Third-party containers can also implement an optional interface ISupportRequiredService which provides the GetRequiredService() method.

比较 用法

  • These methods behave the same when a requested serviceType is available.
  • If the service is not available (i.e. it wasn't registered):
    • GetService() returns null
    • whereas GetRequiredService() throws an InvalidOperationException.

优势 和 推荐

  • The main benefit of GetRequiredService() over GetService() 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.