CodexBloom - Programming Q&A Platform

C# - Circular Reference guide with Dependency Injection in ASP.NET Core 7

πŸ‘€ Views: 459 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-16
asp.net-core dependency-injection c# C#

I'm trying to debug I'm working with a circular reference question while setting up dependency injection in my ASP.NET Core 7 application. I have two services, `UserService` and `NotificationService`, which depend on each other. When I try to run the application, I get an `InvalidOperationException` stating that 'want to consume scoped service `NotificationService` from singleton `UserService`'. I understand that this is due to the nature of their dependencies, but I'm unsure how to refactor this to eliminate the circular dependency. Here's a simplified version of my code: ```csharp public class UserService : IUserService { private readonly INotificationService _notificationService; public UserService(INotificationService notificationService) { _notificationService = notificationService; } public void CreateUser(string username) { // Logic to create user _notificationService.SendNotification(username); } } public class NotificationService : INotificationService { private readonly IUserService _userService; public NotificationService(IUserService userService) { _userService = userService; } public void SendNotification(string username) { // Logic to send notification } } ``` In my `Startup.cs`, I have: ```csharp services.AddSingleton<IUserService, UserService>(); services.AddScoped<INotificationService, NotificationService>(); ``` What’s the best way to resolve this scenario? Should I change one of the services to be Singleton or Scoped? Or is there a better design pattern I can implement to avoid this circular reference? This is happening in both development and production on macOS. Thanks for your help in advance!