Description
I found this in my code (Nullable reference types enabled) multiple times and fixed it, but thought, this could be a good rule.
When dealing with the ServiceCollection and ServiceProvider in .Net, there are the extension methods GetRequiredService<T>() and GetService<T>() (defined in ServiceProviderServiceExtensions).
I used GetService<T>() in cases when constructor injection was not an option and appended the null-forgiving operator, because I forgot that the other method exists.
But when there is the pattern GetService<T>()! used in the code, I think, it's always better to replace it with GetRequiredService<T>().
Reason: If the service does not exist in the collection, you get a NullReferenceException in case of GetService<T>()!, but a more useful InvalidOperationException with a clear message There is no service of type serviceType. in the other case.
Noncompliant code snippet
IServiceProvider sp = GetServiceProvider();
var instance = sp.GetService<ISomeInterface>()!;
Compliant code snippet
IServiceProvider sp = GetServiceProvider();
var instance = sp.GetRequiredService<ISomeInterface>();