CodexBloom - Programming Q&A Platform

Intermittent NullReferenceException When Using Dependency Injection with Scoped Services in .NET 6

πŸ‘€ Views: 112 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-06
dotnet aspnet-core dependency-injection C#

Quick question that's been bugging me - After trying multiple solutions online, I still can't figure this out..... I'm experiencing an intermittent `NullReferenceException` in my .NET 6 application when resolving a scoped service through constructor injection. The service I'm injecting is a repository that interacts with a database context. The error does not occur consistently, but when it does, it seems to happen during web requests where multiple asynchronous calls are involved. Here’s a simplified version of my setup: ```csharp public class MyController : ControllerBase { private readonly IMyRepository _myRepository; public MyController(IMyRepository myRepository) { _myRepository = myRepository; } public async Task<IActionResult> GetDataAsync() { var data = await _myRepository.GetDataAsync(); return Ok(data); } } public interface IMyRepository { Task<List<MyData>> GetDataAsync(); } public class MyRepository : IMyRepository { private readonly MyDbContext _context; public MyRepository(MyDbContext context) { _context = context; } public async Task<List<MyData>> GetDataAsync() { return await _context.MyDatas.ToListAsync(); } } ``` I've registered my repository as a scoped service in `Startup.cs` like this: ```csharp services.AddScoped<IMyRepository, MyRepository>(); ``` The `NullReferenceException` occurs on the `_myRepository` variable during the execution of `GetDataAsync()`. One interesting observation is that it happens more frequently when there are multiple simultaneous requests. I've tried to ensure that the database context is managed correctly, and I don't see any explicit disposal happening on the repository. To troubleshoot, I added some logging: ```csharp public MyController(IMyRepository myRepository, ILogger<MyController> logger) { _myRepository = myRepository ?? throw new ArgumentNullException(nameof(myRepository)); _logger = logger; } ``` Despite this, I still see that `_myRepository` is null in the logs sometimes, which suggests that there's a larger issue with how the dependency injection is handling the scopes. Has anyone else faced a similar issue? Any insights on what could cause the scoped service to be null intermittently would be greatly appreciated. How would you solve this? For context: I'm using C# on Windows. For context: I'm using C# on Linux. This is part of a larger CLI tool I'm building. Has anyone else encountered this?