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.
DI007
resolving dependencies via `IServiceProvider` inside app logic.
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.
Install
dotnet add package DependencyInjection.Lifetime.Analyzers --version 2.2.2
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();
}
Repo sample extraction
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();
}
Related guides
More documentation