DI011

`IServiceProvider` Injection

Constructor injection of IServiceProvider, IServiceScopeFactory, or IKeyedServiceProvider in normal services.

Info Default severity · Code fix: No

Why it matters

This commonly enables hidden runtime resolution and service locator behaviour.

Asking for a giant "surprise box" each time instead of a known tool means no one knows what you actually need.

README problem example

public sealed class MyService
{
    public MyService(IServiceProvider provider) { }
}

Code fix

No. Replacing provider plumbing with explicit dependencies is a design decision.

Repo sample extraction

Examples pulled from the sample app

Open full sample file

Sample app warning case

public class ServiceProviderInjectionExample
{
    private readonly IServiceProvider _provider;

    public ServiceProviderInjectionExample(IServiceProvider provider)
    {
        _provider = provider;
    }

    public void DoWork()
    {
        var service = _provider.GetService<ITransientService>();
    }
}

Sample app safe pattern

public class ExplicitDependencyExample
{
    private readonly ITransientService _service;

    public ExplicitDependencyExample(ITransientService service)
    {
        _service = service;
    }
}

Nearby diagnostics

Other rules in this family

All 37 rules