C# – How to structure an Onion project

cdomain-driven-designonion-architecture

Here is an example implementation using Onion architecture: https://www.codeproject.com/Articles/1028481/Understanding-Onion-Architecture

The webpage suggests a solution structure of:

Domain - Solution Folder
Domain.Entities - Class Library Project
Domain.Interfaces - Class Library Project
Service Interfaces - Solution Folder
Service.Interfaces - Class Library
Services - Solution Folder
Services - Class Library Project
Infrastructure - Solution Folder
Infrastructure.Data - Class Library Project
User Interface - Solution Folder
MVC - MVC Project

I have a few questions:

  1. Why are there two Solution folders in the Service Layer? i.e. Services and Services.Interfaces. I believe there should be one like in the domain layer i.e. the Domain Solution folder contains two class library projects (Domain.Entities and Domain.Interfaces). I would normally put this down to being a mistake, however I have seen other projects structured like that.

  2. Why is the domain and services layer split into two class library projects (why not just have one class library project in each containing classes and libraries).

  3. This question states that ALL interfaces should be contained in the domain layer. However, all the code samples I have looked at put the service layer interfaces in the service layer. Should they go in the service layer or the domain layer?

Best Answer

There is nothing at all required of you from a project/folder perspective to establish an Onion architecture, though the layers in the model do suggest natural places to put project/API boundaries.

Take a look at this diagram:

enter image description here

Now have a look at this one:

enter image description here

Other than the shape of the diagrams, do you notice anything interesting?

The only material difference between these two diagrams is that the Onion diagram only allows access to the database through the Data Access layer. In the "traditional layered architecture," the UI and Business logic are allowed direct access to the database and other IT systems (what the author is calling "infrastructure"). In the Onion Architecture, the only thing allowed access to the database are the Domain Entities. You will note that most of the interaction with this architecture occurs at the Service Layer boundary (the outer ring).

That's all there is to Onion Architecture, really. There's nothing special happening here, other than a stricter separation between layers. In fact, I'd say that the way Onion does it is probably the most common way that business domain software architectures are expressed nowadays. I'd have to go all the way back to Winforms or ASP.NET (both of which use code-behind extensively) to find an architecture that looks more like what this author calls "Traditional Layered."