DI007

Service Locator Anti-Pattern

resolving dependencies via `IServiceProvider` inside app logic.

Default severity: Info · Code fix: No

Why it matters

hides real dependencies, makes tests harder, and weakens architecture boundaries.

If every meal starts with "search the kitchen and see what turns up", dinner becomes chaos.

README problem example

public sealed class MyService
{
    private readonly IServiceProvider _provider;

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

    public void Run()
    {
        var dep = _provider.GetRequiredService<IDependency>();
        dep.Execute();
    }
}

README better pattern

public sealed class MyService
{
    private readonly IDependency _dependency;

    public MyService(IDependency dependency)
    {
        _dependency = dependency;
    }

    public void Run() => _dependency.Execute();
}

No. This is usually architectural refactoring.

Repo sample extraction

Examples pulled from the sample app

Open full sample file

Sample app warning case

public class BadServiceLocatorInConstructor
{
    private readonly IScopedService _scopedService;

    // DI007: Consider injecting 'IScopedService' directly instead of resolving via IServiceProvider
    public BadServiceLocatorInConstructor(IServiceProvider provider)
    {
        _scopedService = provider.GetRequiredService<IScopedService>();
    }

    public void DoWork() => _scopedService.DoWork();
}

Sample app safe pattern

public class GoodConstructorInjection
{
    private readonly IScopedService _scopedService;

    public GoodConstructorInjection(IScopedService scopedService)
    {
        _scopedService = scopedService;
    }

    public void DoWork() => _scopedService.DoWork();
}