Listen to this Post
When working with background jobs in .NET, you might need to resolve scoped services. Here’s how you can achieve this by creating a new scope (IServiceScope):
using (var scope = serviceProvider.CreateScope())
{
var scopedService = scope.ServiceProvider.GetRequiredService<MyScopedService>();
// Use the scoped service here
}
The scope provides its own IServiceProvider, allowing you to resolve scoped services safely. Once the scope is disposed, all services created within it are cleaned up.
You Should Know:
1. Synchronous vs. Async Scopes
- Use `CreateScope()` for synchronous operations.
- Use `CreateAsyncScope()` for asynchronous operations to ensure proper disposal.
2. Explicit `using` for DbContext
While the scope disposes services automatically, explicitly wrapping `DbContext` in a `using` block ensures clarity:
using (var scope = serviceProvider.CreateScope())
{
using (var dbContext = scope.ServiceProvider.GetRequiredService<AppDbContext>())
{
// Database operations
}
}
3. Avoid Capturing Scoped Services
Never capture scoped services in long-running background tasks, as they may be disposed prematurely.
4. Using `IServiceScopeFactory`
Inject `IServiceScopeFactory` for better control over scope creation:
public class BackgroundJob
{
private readonly IServiceScopeFactory _scopeFactory;
public BackgroundJob(IServiceScopeFactory scopeFactory)
{
_scopeFactory = scopeFactory;
}
public void Execute()
{
using (var scope = _scopeFactory.CreateScope())
{
var service = scope.ServiceProvider.GetRequiredService<MyService>();
service.DoWork();
}
}
}
5. Handling Exceptions
Ensure proper exception handling within the scope to avoid resource leaks:
try
{
using (var scope = serviceProvider.CreateScope())
{
var service = scope.ServiceProvider.GetRequiredService<MyService>();
service.Process();
}
}
catch (Exception ex)
{
// Log or handle the exception
}
What Undercode Say:
Managing scoped services in background jobs requires careful attention to resource disposal and lifetime management. Always prefer explicit scoping and avoid holding references to scoped services beyond their intended lifetime. For advanced scenarios, consider using `IHostedService` or third-party libraries like Hangfire, which handle scoping automatically.
Expected Output:
A properly scoped background job that resolves dependencies safely without memory leaks.
Reference: Practical .NET Scoping Tips
References:
Reported By: Milan Jovanovic – Hackers Feeds
Extra Hub: Undercode MoN
Basic Verification: Pass ✅



