Search code examples
c#dependency-injection.net-corearchitecturen-tier-architecture

Avoid cyclic dependency in n-layer architecture in .NET Core


I have created such n-layer architecture in .net core (console app):

Company.App
   -> reference to Company.Services
   -> reference to Company.Infrastructure

Company.Services
   -> reference to Company.Infrastructure

   + IWorkStarter
   + WorkStarter - (ExternalClient is injected)

Company.Infrastructure
   + RabbitMqConsumer - (IWorkStarter must be injected) - Cyclic dependency
   + IExternalClient

As you see Services already has a reference to Infrastructure. And I have to use IWorkStarter inside rabbit consumer as well. It seems I have no required knowledge to separate those components in a right way. Could you please help me? The project is quite simple.


Solution

  • Following a design I see frequently in Clean Architecture (Onion Architecture) with ASP.NET Core.

    Review the following

    Company.App
       -> reference to Company.Services
       -> reference to Company.Infrastructure
       -> reference to Company.Core
    
        + Compsition Root maps everything
       
    Company.Services
       -> reference to Company.Infrastructure
       -> reference to Company.Core
    
       + WorkStarter - (ExternalClient is injected)
    
    Company.Infrastructure
       -> reference to Company.Core
       
       + RabbitMqConsumer - (IWorkStarter must be injected)
       
    Company.Core
       + IWorkStarter
       + IExternalClient
    

    Move the abstractions out into their own concern

    The following reference repository provides a good example

    https://github.com/ardalis/CleanArchitecture

    The Core Project

    The Core project is the center of the Clean Architecture design, and all other project dependencies should point toward it. As such, it has very few external dependencies.