Dependency Injection is one of the core features of ASP.NET Core. It helps developers manage object creation, reduce tight coupling, and build applications that are easier to test and maintain.
In most ASP.NET Core applications, developers register services in the dependency injection container and request them through constructor injection. The framework takes care of creating the required objects and providing their dependencies.
However, as an application grows, service relationships can become complicated. A service may depend on another service, which eventually depends on the original service. This creates a circular dependency.
For example, imagine an OrderService that needs InventoryService to check product availability. At the same time, InventoryService needs OrderService to retrieve order information.
Both services depend on each other.
When ASP.NET Core tries to create these services, it cannot complete the dependency resolution process. The application may throw an exception similar to the following:
System.InvalidOperationException:
A circular dependency was detected for the service
of type 'IOrderService'.
IOrderService
-> IInventoryService
-> IOrderService
This error can be confusing, especially when the application contains multiple layers of services and repositories.
The problem is not necessarily with dependency injection itself. In most cases, it indicates that the application has a dependency relationship that needs to be reconsidered.
In this article, we'll understand why circular dependencies occur in ASP.NET Core, how to identify them, and how to fix them using practical approaches such as refactoring services, introducing separate responsibilities, using events, and applying better architectural patterns.
We'll also look at common workarounds that developers should avoid.
Understanding Circular Dependencies in ASP.NET Core
Before fixing the problem, let's understand how circular dependencies happen.
Dependency Injection allows one class to receive another class as a dependency instead of creating that dependency manually.
For example, consider an OrderService that requires an IOrderRepository.
public interface IOrderRepository
{
Task CreateAsync(Order order);
}
public class OrderService : IOrderService
{
private readonly IOrderRepository _orderRepository;
public OrderService(IOrderRepository orderRepository)
{
_orderRepository = orderRepository;
}
public async Task CreateOrderAsync(Order order)
{
await _orderRepository.CreateAsync(order);
}
}
The OrderService does not create the repository itself. ASP.NET Core provides the required implementation through dependency injection.
We can register the services in Program.cs:
builder.Services.AddScoped<IOrderRepository, OrderRepository>();
builder.Services.AddScoped<IOrderService, OrderService>();
This is a normal dependency relationship.
OrderService depends on IOrderRepository, and the repository does not depend on OrderService.
The dependency graph looks like this:
OrderService
|
v
IOrderRepository
|
v
OrderRepository
ASP.NET Core can resolve this dependency without any problem.
Now imagine that another service is introduced.
The OrderService depends on InventoryService, and InventoryService also depends on OrderService.
The dependency graph becomes:
OrderService
|
v
InventoryService
|
v
OrderService
This is a circular dependency.
When the dependency injection container tries to create OrderService, it first needs InventoryService.
To create InventoryService, it needs OrderService again.
The container cannot complete the object creation process because the dependency chain leads back to the service that is already being constructed.
This is why ASP.NET Core reports a circular dependency error.
A Practical Example of a Circular Dependency
Let's build a simple example using an e-commerce application.
Suppose the application contains two services:
- OrderService
- InventoryService
The OrderService handles order creation and needs to check whether products are available.
The InventoryService manages stock information and needs to retrieve order information when processing inventory adjustments.
A developer might implement these services as follows.
OrderService Implementation
public interface IOrderService
{
Task CreateOrderAsync(int productId, int quantity);
}
public class OrderService : IOrderService
{
private readonly IInventoryService _inventoryService;
public OrderService(IInventoryService inventoryService)
{
_inventoryService = inventoryService;
}
public async Task CreateOrderAsync(
int productId,
int quantity)
{
var available = await _inventoryService
.IsProductAvailableAsync(productId, quantity);
if (!available)
{
throw new InvalidOperationException(
"Product is out of stock.");
}
// Continue order creation.
}
}
The OrderService depends on IInventoryService because it needs to check product availability before creating an order.
InventoryService Implementation
Now consider the InventoryService:
public interface IInventoryService
{
Task<bool> IsProductAvailableAsync(
int productId,
int quantity);
}
public class InventoryService : IInventoryService
{
private readonly IOrderService _orderService;
public InventoryService(IOrderService orderService)
{
_orderService = orderService;
}
public async Task<bool> IsProductAvailableAsync(
int productId,
int quantity)
{
// Inventory validation logic.
return true;
}
}
Here, InventoryService depends on IOrderService.
Both classes use constructor injection, but their dependencies create a cycle.
Registering the Services
In Program.cs:
builder.Services.AddScoped<IOrderService, OrderService>();
builder.Services.AddScoped<IInventoryService, InventoryService>();
The registrations themselves are valid.
The problem becomes visible when the application tries to resolve IOrderService.
The dependency chain looks like this:
IOrderService
|
v
OrderService
|
v
IInventoryService
|
v
InventoryService
|
v
IOrderService
ASP.NET Core cannot construct these services because each one requires the other to exist first.
The important thing to understand is that registering services with Scoped, Transient, or Singleton lifetime does not solve this problem.
The dependency relationship itself needs to change.
How to Identify Circular Dependency Errors
Before changing the application architecture, developers should understand where the circular dependency is occurring.
ASP.NET Core usually reports a circular dependency through an InvalidOperationException when the dependency injection container attempts to resolve the affected service.
A typical error looks like this:
System.InvalidOperationException:
A circular dependency was detected for the service
of type 'IOrderService'.
IOrderService
-> IInventoryService
-> IOrderService
The exception contains useful information about the dependency chain.
For example:
IOrderService
-> IInventoryService
-> IPaymentService
-> IOrderService
This indicates that the dependency cycle involves three services.
The first service depends on the second, the second depends on the third, and the third eventually depends on the first.
In larger applications, the cycle may involve several layers:
Controller
|
v
OrderService
|
v
PaymentService
|
v
NotificationService
|
v
OrderService
In this situation, looking only at OrderService may not immediately reveal the problem.
Developers should inspect the constructors of all services mentioned in the exception.
A useful debugging approach is:
- Identify the first service mentioned in the exception.
- Follow each dependency in the reported chain.
- Open the corresponding service constructors.
- Check which constructor parameter introduces the next dependency.
- Continue until the dependency leads back to the original service.
Also check indirect dependencies. Two services do not need to reference each other directly to create a circular dependency.
For example, A can depend on B, B can depend on C, and C can depend on A.
Fixing Circular Dependencies by Refactoring Service Responsibilities
One of the best ways to fix circular dependencies is to reconsider what each service is responsible for.
In many applications, circular dependencies appear because services have gradually accumulated responsibilities that belong somewhere else.
Let's revisit our OrderService and InventoryService example.
The OrderService needs inventory information to create an order.
The InventoryService should manage stock operations.
But why does InventoryService need OrderService?
If it only needs order information to update inventory, perhaps it should receive the required order data directly instead of depending on the entire OrderService.
This is an opportunity to simplify the design.
Separate the Responsibilities
Instead of allowing InventoryService to retrieve order information through OrderService, we can introduce a separate service or repository responsible for accessing the required data.
For example, create an IOrderRepository:
public interface IOrderRepository
{
Task<Order?> GetByIdAsync(int orderId);
Task CreateAsync(Order order);
}
Its implementation handles order data access:
public class OrderRepository : IOrderRepository
{
private readonly AppDbContext _dbContext;
public OrderRepository(AppDbContext dbContext)
{
_dbContext = dbContext;
}
public async Task<Order?> GetByIdAsync(int orderId)
{
return await _dbContext.Orders
.FirstOrDefaultAsync(o => o.Id == orderId);
}
public async Task CreateAsync(Order order)
{
await _dbContext.Orders.AddAsync(order);
await _dbContext.SaveChangesAsync();
}
}
Now InventoryService can depend directly on the repository if it genuinely needs to retrieve order data.
public class InventoryService : IInventoryService
{
private readonly IOrderRepository _orderRepository;
public InventoryService(IOrderRepository orderRepository)
{
_orderRepository = orderRepository;
}
public async Task<bool> IsProductAvailableAsync(
int productId,
int quantity)
{
// Inventory validation logic.
return true;
}
}
The OrderService can continue depending on InventoryService.
public class OrderService : IOrderService
{
private readonly IInventoryService _inventoryService;
private readonly IOrderRepository _orderRepository;
public OrderService(
IInventoryService inventoryService,
IOrderRepository orderRepository)
{
_inventoryService = inventoryService;
_orderRepository = orderRepository;
}
public async Task CreateOrderAsync(
int productId,
int quantity)
{
var available = await _inventoryService
.IsProductAvailableAsync(productId, quantity);
if (!available)
{
throw new InvalidOperationException(
"Product is out of stock.");
}
var order = new Order
{
ProductId = productId,
Quantity = quantity
};
await _orderRepository.CreateAsync(order);
}
}
Now the dependency graph looks like this:
OrderService
|
+--------------------+
| |
v v
InventoryService OrderRepository
|
v
AppDbContext
InventoryService no longer depends on OrderService.
The circular dependency has been removed.
There is an important architectural consideration here.
Introducing a repository is not automatically the correct solution for every circular dependency. The repository should represent a genuine data access responsibility. Avoid creating additional abstractions just to hide an existing dependency cycle.
The real objective is to make sure each service has a clear responsibility and depends only on what it actually needs.
Introduce a Separate Orchestration Service
Another common situation occurs when two services are responsible for different parts of a business workflow but both need to coordinate with each other.
Instead of making them depend on each other, introduce a third service that coordinates the operation.
This approach is particularly useful when a business operation involves multiple services.
Consider the following workflow:
- Validate product availability.
- Create an order.
- Update inventory.
- Send an order confirmation.
A developer might place some of this logic in OrderService and some in InventoryService. Over time, both services may start calling each other.
A better approach is to introduce an OrderProcessingService.
This service coordinates the workflow, while the individual services handle their own responsibilities.
The dependency structure becomes:
OrderProcessingService
|
+-----+------+
| |
v v
OrderService InventoryService
Let's implement it.
First, define the OrderService:
public interface IOrderService
{
Task<Order> CreateAsync(
int productId,
int quantity);
}
public class OrderService : IOrderService
{
private readonly IOrderRepository _repository;
public OrderService(IOrderRepository repository)
{
_repository = repository;
}
public async Task<Order> CreateAsync(
int productId,
int quantity)
{
var order = new Order
{
ProductId = productId,
Quantity = quantity
};
await _repository.CreateAsync(order);
return order;
}
}
The InventoryService handles inventory operations:
public interface IInventoryService
{
Task<bool> IsAvailableAsync(
int productId,
int quantity);
Task ReduceStockAsync(
int productId,
int quantity);
}
public class InventoryService : IInventoryService
{
public Task<bool> IsAvailableAsync(
int productId,
int quantity)
{
// Check available stock.
return Task.FromResult(true);
}
public Task ReduceStockAsync(
int productId,
int quantity)
{
// Reduce available stock.
return Task.CompletedTask;
}
}
Now introduce the orchestration service:
public class OrderProcessingService
{
private readonly IOrderService _orderService;
private readonly IInventoryService _inventoryService;
public OrderProcessingService(
IOrderService orderService,
IInventoryService inventoryService)
{
_orderService = orderService;
_inventoryService = inventoryService;
}
public async Task ProcessOrderAsync(
int productId,
int quantity)
{
var available = await _inventoryService
.IsAvailableAsync(productId, quantity);
if (!available)
{
throw new InvalidOperationException(
"Insufficient inventory.");
}
await _orderService.CreateAsync(productId, quantity);
await _inventoryService.ReduceStockAsync(
productId,
quantity);
}
}
Register the services:
builder.Services.AddScoped<IOrderService, OrderService>();
builder.Services.AddScoped<IInventoryService, InventoryService>();
builder.Services.AddScoped<OrderProcessingService>();
The controller can now depend on OrderProcessingService:
[ApiController]
[Route("api/orders")]
public class OrdersController : ControllerBase
{
private readonly OrderProcessingService _orderProcessingService;
public OrdersController(
OrderProcessingService orderProcessingService)
{
_orderProcessingService = orderProcessingService;
}
[HttpPost]
public async Task<IActionResult> Create(
int productId,
int quantity)
{
await _orderProcessingService.ProcessOrderAsync(
productId,
quantity);
return Ok("Order processed successfully.");
}
}
This design keeps the workflow in one place.
OrderService manages order creation, InventoryService manages stock, and OrderProcessingService coordinates the operation.
In a real application, order creation and stock reduction may need to be performed within a database transaction or through a more resilient workflow. If they involve different services or databases, a distributed transaction or saga-style approach may be necessary.
The important point is that the services no longer need to call each other directly.
Use Events to Reduce Direct Service Dependencies
Sometimes one service needs to notify another service that something has happened.
For example, after an order is created, the application may need to:
- Update inventory.
- Send an email confirmation.
- Generate an invoice.
- Update reporting information.
- Publish a notification.
One approach is to inject all these services directly into OrderService.
As the application grows, this can create a large number of dependencies.
It can also introduce circular dependencies if some of those services eventually require order-related operations.
An alternative is to use events.
Instead of directly calling another service, OrderService publishes an event indicating that an order has been created.
Other components can respond to that event.
Define an Order Created Event
public record OrderCreatedEvent(
int OrderId,
int ProductId,
int Quantity);
Publish the Event From OrderService
For this example, we'll use MediatR's notification mechanism.
First, define the notification:
using MediatR;
public record OrderCreatedNotification(
int OrderId,
int ProductId,
int Quantity) : INotification;
The OrderService can publish the notification after creating an order:
public class OrderService : IOrderService
{
private readonly IOrderRepository _repository;
private readonly IMediator _mediator;
public OrderService(
IOrderRepository repository,
IMediator mediator)
{
_repository = repository;
_mediator = mediator;
}
public async Task CreateOrderAsync(
Order order)
{
await _repository.CreateAsync(order);
await _mediator.Publish(
new OrderCreatedNotification(
order.Id,
order.ProductId,
order.Quantity));
}
}
Handle the Event in InventoryService
Now InventoryService can handle the notification without being directly referenced by OrderService.
public class OrderCreatedHandler :
INotificationHandler<OrderCreatedNotification>
{
private readonly IInventoryService _inventoryService;
public OrderCreatedHandler(
IInventoryService inventoryService)
{
_inventoryService = inventoryService;
}
public async Task Handle(
OrderCreatedNotification notification,
CancellationToken cancellationToken)
{
await _inventoryService.ReduceStockAsync(
notification.ProductId,
notification.Quantity);
}
}
Register MediatR and the application services according to the installed MediatR version and its registration API.
The dependency graph now looks like this:
OrderService
|
v
IMediator
|
v
OrderCreatedNotification
|
v
OrderCreatedHandler
|
v
InventoryService
OrderService does not need to know which components handle the notification.
This reduces direct dependencies and makes it easier to add new operations when an order is created.
However, there is an important distinction between in-process notifications and reliable messaging.
MediatR notifications execute within the application process. Publishing a notification does not automatically guarantee that all related operations will succeed or that the event will survive an application crash.
For important business operations, consider transaction handling and the transactional outbox pattern.
For example, if an order is saved successfully but inventory processing fails, the application needs a reliable way to retry the operation.
An outbox stores the event in the same database transaction as the business change. A background process can then publish pending events reliably.
Use in-process notifications for operations that fit the application lifecycle, and use durable messaging when business reliability requires it.
Use Interfaces Correctly Without Assuming They Fix Circular Dependencies
A common misunderstanding is that replacing concrete class dependencies with interfaces automatically fixes circular dependencies.
Interfaces are useful because they reduce coupling between implementations.
For example:
public class OrderService : IOrderService
{
private readonly IInventoryService _inventoryService;
public OrderService(IInventoryService inventoryService)
{
_inventoryService = inventoryService;
}
}
And:
public class InventoryService : IInventoryService
{
private readonly IOrderService _orderService;
public InventoryService(IOrderService orderService)
{
_orderService = orderService;
}
}
Although both classes depend on interfaces, the dependency graph is still circular.
IOrderService
|
v
IInventoryService
|
v
IOrderService
The dependency injection container resolves implementations, not just interface names.
Therefore, changing concrete dependencies into interfaces does not remove a circular dependency when the underlying relationship remains the same.
Interfaces should be introduced to establish meaningful contracts between components, not simply to make circular dependencies disappear.
Use Factory-Based Resolution Only When There Is a Genuine Runtime Need
Another approach developers sometimes consider is resolving dependencies through IServiceProvider.
For example:
public class InventoryService : IInventoryService
{
private readonly IServiceProvider _serviceProvider;
public InventoryService(IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
}
public async Task ProcessInventoryAsync(int orderId)
{
var orderService =
_serviceProvider.GetRequiredService<IOrderService>();
// Process inventory.
}
}
At first glance, this appears to remove the constructor dependency on IOrderService.
However, the underlying dependency still exists.
InventoryService still requires OrderService. It simply resolves it at runtime instead of through constructor injection.
This hides the dependency from the constructor and makes the service harder to understand and test.
It also introduces the service locator pattern, which Microsoft generally recommends avoiding when normal dependency injection can be used.
There are legitimate situations where a factory is appropriate.
For example, an application might need to create a service dynamically based on a runtime value.
In such cases, a dedicated factory with a clear responsibility can be useful.
But using IServiceProvider merely to bypass a circular dependency is not a proper architectural fix.
First, identify why the services depend on each other. Then separate their responsibilities or introduce an appropriate coordination mechanism.
Check Service Lifetimes, but Don't Confuse Lifetime Errors With Circular Dependencies
ASP.NET Core supports three common service lifetimes:
Developers sometimes try changing service lifetimes when they encounter a circular dependency.
For example, they may change one service from Scoped to Singleton or Transient, hoping the error will disappear.
This does not fix the underlying dependency cycle.
A circular dependency is about the relationship between services, not how long their instances live.
However, service lifetime configuration is still important because incorrect lifetimes can introduce other dependency injection errors.
Transient Services
A transient service is created each time it is requested from the dependency injection container.
Register it using:
builder.Services.AddTransient<IOrderService, OrderService>();
Transient services are useful for lightweight, stateless operations.
Scoped Services
A scoped service is generally created once per request in an ASP.NET Core web application.
Register it using:
builder.Services.AddScoped<IOrderService, OrderService>();
This lifetime is commonly used for application services and EF Core DbContext instances.
By default, AddDbContext registers DbContext as scoped.
Singleton Services
A singleton service is created once and reused for the lifetime of the application.
Register it using:
builder.Services.AddSingleton<IOrderService, OrderService>();
Singleton services must be designed for concurrent access when they are used by multiple requests.
They should not directly capture scoped dependencies through constructor injection.
For example, a singleton service that depends on a scoped DbContext can produce a captive dependency problem.
This is different from a circular dependency, but it is another important issue to understand when configuring the dependency injection container.
If a singleton genuinely needs to use scoped services, create an explicit scope using IServiceScopeFactory and resolve the scoped dependencies within that scope.
Enable Dependency Injection Validation
Another useful practice is enabling dependency injection validation so that configuration problems can be detected during application startup.
ASP.NET Core supports validation of service registrations and service scopes.
For example, you can configure the default service provider:
var builder = WebApplication.CreateBuilder(args);
builder.Host.UseDefaultServiceProvider(options =>
{
options.ValidateScopes = true;
options.ValidateOnBuild = true;
});
ValidateScopes checks for certain lifetime-related problems, such as a singleton depending on a scoped service.
ValidateOnBuild validates registered service call sites when the service provider is built, where applicable.
These options are useful for catching dependency configuration issues earlier instead of discovering them during a request.
However, validation is not a replacement for proper service design. Not every possible runtime resolution path or dynamically created dependency can be validated at startup.
Also, avoid calling BuildServiceProvider() manually inside service registration code to test or resolve services. Creating additional service providers can result in duplicate singleton instances and inconsistent service lifetimes.
How to Prevent Circular Dependencies in Large ASP.NET Core Applications
Fixing one circular dependency is useful, but preventing the same problem from appearing elsewhere is even more important.
As applications grow, services tend to accumulate responsibilities. A service that originally handled one operation may eventually become responsible for several unrelated workflows.
This can create complex dependency chains.
The following practices can help keep the dependency structure manageable.
Keep Services Focused on One Responsibility
A service should have a clear purpose.
For example:
- OrderService should manage order-related operations.
- InventoryService should manage inventory-related operations.
- PaymentService should manage payment operations.
- NotificationService should manage notifications.
Avoid making one service responsible for coordinating every part of the application.
If a workflow involves multiple services, consider introducing a separate application service to coordinate the operation.
Avoid Bidirectional Dependencies Between Application Services
When two services depend on each other, take a closer look at their responsibilities.
Ask whether one service is performing work that belongs somewhere else.
If both services need information from the same database, a repository or query service may be appropriate.
If they need to coordinate a business workflow, an orchestration service may be a better option.
If one service only needs to react to something that happened, consider using an event.
Separate Business Logic From Data Access
Avoid mixing database access, business rules, and workflow coordination in the same service.
Separating these responsibilities makes dependencies easier to understand.
For example, an OrderService can coordinate order creation, while an OrderRepository handles persistence.
Similarly, a reporting service can retrieve reporting data without depending on the entire order-processing workflow.
This does not mean every application needs a repository for every entity. The goal is to introduce boundaries where they provide real value.
Be Careful With Large Service Constructors
If a service requires ten or fifteen dependencies, it may be handling too many responsibilities.
For example:
public class OrderService
{
public OrderService(
IOrderRepository orderRepository,
IInventoryService inventoryService,
IPaymentService paymentService,
IEmailService emailService,
ISmsService smsService,
IInvoiceService invoiceService,
IShippingService shippingService)
{
}
}
A large constructor does not automatically indicate a circular dependency.
However, it can be a sign that the service is doing too much.
Consider separating responsibilities into smaller services or introducing an application-level workflow coordinator.
Keep Dependency Direction Consistent
A well-structured application should have clear dependency boundaries.
For example, controllers can depend on application services, and application services can depend on data access abstractions.
Avoid creating unnecessary dependencies in the opposite direction.
A simple structure might look like this:
API Layer
|
v
Application Layer
|
v
Domain Layer
Infrastructure Layer
|
v
Implements Application Contracts
The exact structure depends on the architecture, but dependencies should remain intentional and predictable.
Common Mistakes Developers Should Avoid
There are several approaches that may appear to solve circular dependency errors but can create additional problems.
Changing Service Lifetimes Without Changing Dependencies
Changing Scoped to Transient or Singleton does not remove a circular dependency.
Always inspect the dependency graph first.
Replacing Concrete Classes With Interfaces and Assuming the Problem Is Fixed
Interfaces improve abstraction, but they do not automatically remove dependency cycles.
The implementation relationships still matter.
Injecting IServiceProvider Everywhere
Using IServiceProvider to resolve dependencies dynamically can hide the actual dependencies of a service.
Prefer constructor injection and use dedicated factories only when runtime creation is genuinely required.
Introducing Too Many Repositories
Repositories can help separate data access from business logic, but adding a repository for every circular dependency without understanding the design can create unnecessary complexity.
Use abstractions where they represent meaningful responsibilities.
Moving All Business Logic Into Controllers
Moving logic from services into controllers may temporarily remove a dependency, but it creates another problem.
Controllers should primarily handle HTTP requests and responses. Business workflows belong in application services or other appropriate components.
Ignoring Indirect Dependencies
A dependency cycle may involve three, four, or more services.
Do not inspect only the two classes that appear to be related. Follow the complete dependency chain reported by the exception.
Conclusion
Circular dependency errors in ASP.NET Core usually indicate that two or more services depend on each other, either directly or through an intermediate service.
The dependency injection container cannot complete the object creation process when the dependency chain leads back to a service that is already being constructed.
The best way to fix this problem is to examine the dependency graph and understand why the services depend on each other.
In many cases, separating responsibilities or introducing an orchestration service is enough to remove the cycle. When services need to react to business events, event-driven communication can reduce direct dependencies. Repositories and other abstractions can also help when they represent genuine architectural boundaries.
Avoid using IServiceProvider simply to hide circular dependencies, and do not expect changing service lifetimes or introducing interfaces alone to solve the problem.
Most importantly, keep services focused, maintain clear dependency boundaries, and validate your dependency injection configuration.
A good dependency injection design should make it easy to understand how services interact without requiring one service to know too much about another.
Join the conversation! Your thoughts help the community grow.