Skip to content

NET-2375 New Rule Idea: Use GetRequiredService<T>() instead of the pattern GetService<T>()! (in case of NRT) #9759

@ndsvw

Description

@ndsvw

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    Rule IdeaIdea for a rule that has NOT been specified.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions