تخطَّ إلى المحتوى

Captured scoped service (ARCH501)

هذا المحتوى غير متوفر بلغتك بعد.

Key dotnet.di.captured-scoped-service · Severity error · Category di · Principle DependencyInversion

Singleton services should not capture scoped services via constructor injection. Doing so makes the scoped service behave like a singleton and leaks the scope.

public class CacheManager
{
private readonly OrderDbContext _context;
public CacheManager(OrderDbContext context) // scoped, inside a singleton
{
_context = context;
}
}
public class CacheManager
{
private readonly IServiceScopeFactory _scopeFactory;
public CacheManager(IServiceScopeFactory scopeFactory)
{
_scopeFactory = scopeFactory;
}
public void Refresh()
{
using var scope = _scopeFactory.CreateScope();
var context = scope.ServiceProvider.GetRequiredService<OrderDbContext>();
}
}

Access the scoped service from within the singleton by creating a scope through IServiceScopeFactory. If needed, suppress the rule per project/workspace via except/ignore.