I build a minimal template for a web application according to clean architecture principals. I will use the following technologies: ASP.NET MVC 5, Entity Framework 6 for persistence.
Sample application is available here https://github.com/mchudinov/AspMvc5Minimal
Let’s build a web application using architectural principals by Robert Martin as he writes in this blog post: The Clean Architecture.
0. Create a blank Visual Studio solution first
1. Define solution structure
We need the following projects in our application solution (at least one project per tier):
- Models – the only project for entities definitions
- UseCases – this project contains application specific business rules
- Repositories – this is a persistent layer with CRUD activity for entities.
- Gui – this is ASP.NET MVC itself, all the controllers, views and view-models are here
2. Define data models
Use only Models project to define models.
For applications that are build from scratch use only models first approach.
- Define models
- Define models relations
- Define models constraints
Consider to use GUIDs as identifiers for entities with potentially unlimited amount.
Initialise GUIDs in models constructors.
Consider to use integers as identifiers for entities with limited or just small amount.
[DatabaseGenerated(DatabaseGeneratedOption.Identity)] annotation for auto-increment fields.
Mark connection (foreign-key) properties as virtual.
3. Define repositories
Repositories add persistent. Application will use only repositories to connect to persistent layer.
- Define abstract CRUD repositories (interfaces) first. Consider one repository per model.
- Choose persistent layer connector: LINQ – simplicity, Entity Framework – transaction support.
- Define database context
- Define connection string in Gui project. Use Gui project as StartProject in migrations later.
- Define concrete implementations based on the chosen persistent layer technology.
Run the following commands in Package Manager Console to start migrations:
Enable-Migrations -Verbose -ContextProjectName Repositories -StartUpProjectName Gui -ProjectName Repositories -ConnectionStringName AppDb
Add-migration Init -Verbose -StartUpProjectName Gui -ProjectName Repositories -ConnectionStringName AppDb
Update-Database -Verbose -StartUpProjectName Gui -ProjectName Repositories -ConnectionStringName AppDb
4. Define Use Cases
Use cases must be in a separate project. Use cases can be like Register_New_User, CreateSomething etc.
- Define interfaces for use cases.
- Define concrete implementations using repositories. Each use case can use multiple repositories.
Use Cases must not be dependent on concrete repositories. They should use repository interfaces.
5. Build Gui
- Define routing pattern in App_Start\RouteConfig.cs
- Build simple ‘list’ controllers first.
- Create views for simple list controllers.