SlideShare une entreprise Scribd logo
1  sur  72
Applying Clean
Architecture to ASP.NET
Core Apps
STEVE SMITH
ARDALIS.COM | @ARDALIS | STEVE@ARDALIS.COM
MENTOR | TRAINER | COACH | FORCE MULTIPLIER
Applying Clean Architecture to ASP.NET Core | @ardalis
Welcome SLC-NET Folks!
Applying Clean Architecture to ASP.NET Core | @ardalis
Literally 10 minutes before starting…
Applying Clean Architecture to ASP.NET Core | @ardalis
Literally 10 minutes before starting…
Applying Clean Architecture to ASP.NET Core | @ardalis
Learn More After Today
1) Pluralsight – FREE in April 2020
◦ Domain-Driven Design Fundamentals
https://www.pluralsight.com/courses/domain-driven-design-fundamentals
2) Microsoft FREE eBook/Sample App (updated for .NET Core 3.1)
◦ eShopOnWeb eCommerce Sample https://ardalis.com/architecture-ebook
3) Contact me for mentoring/training for your company/team
4) Developer Career Mentoring at devBetter.com
Applying Clean Architecture to ASP.NET Core | @ardalis
Weekly Dev Tips
Podcast and Newsletter (and stream)
 Ardalis.com/tips
 WeeklyDevTips.com
Streaming at twitch.tv/ardalis Fridays
Applying Clean Architecture to ASP.NET Core | @ardalis
Questions
HOPEFULLY YOU’LL KNOW THE ANSWERS WHEN WE’RE DONE
Applying Clean Architecture to ASP.NET Core | @ardalis
Why do we separate applications into multiple
projects?
Applying Clean Architecture to ASP.NET Core | @ardalis
What are some principles we can apply when
organizing our software modules?
Applying Clean Architecture to ASP.NET Core | @ardalis
How does the organization of our application’s
solution impact coupling?
Applying Clean Architecture to ASP.NET Core | @ardalis
What problems result from certain common
approaches?
Applying Clean Architecture to ASP.NET Core | @ardalis
How does Clean Architecture address these
problems?
Applying Clean Architecture to ASP.NET Core | @ardalis
How does ASP.NET Core help?
Applying Clean Architecture to ASP.NET Core | @ardalis
Principles
A BIT OF GUIDANCE
Separation of Concerns
Avoid mixing different code responsibilities in the
same (method | class | project)
Applying Clean Architecture to ASP.NET Core | @ardalis
Separation of Concerns
The Big Three™
Data Access
Business Rules and Domain Model
User Interface
Applying Clean Architecture to ASP.NET Core | @ardalis
Applying Clean Architecture to ASP.NET Core | @ardalis
Single Responsibility
Works in tandem with Separation of Concerns
Classes should focus on a single responsibility – a
single reason to change.
Applying Clean Architecture to ASP.NET Core | @ardalis
Applying Clean Architecture to ASP.NET Core | @ardalis
Following Don’t Repeat Yourself…
Refactor repetitive code into functions
Group functions into cohesive classes
Group classes into folders and namespaces by
 Responsibility
 Level of abstraction
 Etc.
Further group class folders into projects
Applying Clean Architecture to ASP.NET Core | @ardalis
Applying Clean Architecture to ASP.NET Core | @ardalis
Invert (and inject) Dependencies
Both high level classes and implementation-detail classes should
depend on abstractions (interfaces).
Applying Clean Architecture to ASP.NET Core | @ardalis
Invert (and inject) Dependencies
Classes should follow Explicit Dependencies Principle:
Request all dependencies via their constructor
Make your types honest, not deceptive
Applying Clean Architecture to ASP.NET Core | @ardalis
Invert (and inject) Dependencies
Corollary: Abstractions/interfaces must be defined somewhere accessible by:
Low level implementation services
High level business services
User interface entry points
Applying Clean Architecture to ASP.NET Core | @ardalis
Applying Clean Architecture to ASP.NET Core | @ardalis
Applying Clean Architecture to ASP.NET Core | @ardalis
Make the right thing easy
and the wrong thing hard
FORCE DEVELOPERS INTO A “PIT OF SUCCESS”
Applying Clean Architecture to ASP.NET Core | @ardalis
Applying Clean Architecture to ASP.NET Core | @ardalis
Make the right thing easy and the wrong thing hard.
UI classes shouldn’t depend directly on infrastructure classes
◦ How can we structure our solution to help enforce this?
Applying Clean Architecture to ASP.NET Core | @ardalis
Make the right thing easy and the wrong thing hard.
Business/domain classes shouldn’t depend on infrastructure classes
◦ How can our solution design help?
Applying Clean Architecture to ASP.NET Core | @ardalis
Make the right thing easy and the wrong thing hard.
Repetition of (query logic, validation logic, policies, error handling, anything) is a problem
◦ What patterns can we apply to make avoiding repetition easier
than copy/pasting?
Applying Clean Architecture to ASP.NET Core | @ardalis
“Classic” N-Tier
Architecture
OR N-LAYER
Layer
Layer
Layer
Applying Clean Architecture to ASP.NET Core | @ardalis
Source: MSDN Website, 2001
Applying Clean Architecture to ASP.NET Core | @ardalis
Transitive Dependencies
DB
Data Access
Layer
Business Logic
Layer
User Interface
Layer
Everything
Depends on the database
Applying Clean Architecture to ASP.NET Core | @ardalis
Applying Clean Architecture to ASP.NET Core | @ardalis
Domain-Centric
Design
AND THE CLEAN ARCHITECTURE
Core
Business
Logic
Everything
Else
Applying Clean Architecture to ASP.NET Core | @ardalis
Domain Model
Not just business logic, but also:
A model of the problem space composed of Entities, Interfaces, Services, and
more.
Interfaces define contracts for working with domain objects
Everything in the application (including infrastructure and data access) depends
on these interfaces and domain objects
Applying Clean Architecture to ASP.NET Core | @ardalis
Clean Architecture
Onion Architecture
Hexagonal Architecture
Ports and Adapters
Applying Clean Architecture to ASP.NET Core | @ardalis
Applying Clean Architecture to ASP.NET Core | @ardalis
Applying Clean Architecture to ASP.NET Core | @ardalis
Clean Architecture “Rules”
1. You do not talk about Clean Architecture.
Applying Clean Architecture to ASP.NET Core | @ardalis
Clean Architecture “Rules”
1. You do not talk about Clean Architecture.
Applying Clean Architecture to ASP.NET Core | @ardalis
Clean Architecture “Rules”
The Application Core contains the Domain Model
Applying Clean Architecture to ASP.NET Core | @ardalis
Clean Architecture “Rules”
All projects depend on the Core project;
dependencies point inward toward this core
Applying Clean Architecture to ASP.NET Core | @ardalis
Clean Architecture “Rules”
Inner projects define interfaces;
Outer projects implement them
Applying Clean Architecture to ASP.NET Core | @ardalis
Clean Architecture “Rules”
Avoid direct dependency on the Infrastructure project
(except from Integration Tests and possibly Startup.cs)
Applying Clean Architecture to ASP.NET Core | @ardalis
Clean Architecture Features
Framework Independent
◦ You can use this architecture with ASP.NET (Core), Java, Python,
etc.
◦ It doesn’t rely on any software library or proprietary codebase.
Applying Clean Architecture to ASP.NET Core | @ardalis
Clean Architecture Features
Database Independent
◦ The vast majority of the code has no knowledge of persistence
details.
◦ This knowledge may exist in just one class, in one project that no
other project references.
Applying Clean Architecture to ASP.NET Core | @ardalis
Clean Architecture Features
UI Independent
◦ Only the UI project cares about the UI.
◦ The rest of the system is UI-agnostic.
Applying Clean Architecture to ASP.NET Core | @ardalis
Clean Architecture Features
Testable
◦ Apps built using this approach, and especially the core domain
model and its business rules, are easy to test.
Applying Clean Architecture to ASP.NET Core | @ardalis
Refactoring to a Clean Architecture
Best to start from a properly organized solution
◦ See https://github.com/ardalis/CleanArchitecture
Next-best: Start from an application consisting of just a single project
Most difficult: Large, existing investment in multi-layer architecture without
abstractions or DI
Applying Clean Architecture to ASP.NET Core | @ardalis
The Core Project (domain model)
Minimal dependencies – none on Infrastructure.
What Goes in Core:
Interfaces
Entities Value Objects Aggregates
Domain
Services
Domain Events
Exceptions
Specifications
Event Handlers
Applying Clean Architecture to ASP.NET Core | @ardalis
The Infrastructure Project
All dependencies on out-of-process resources.
What Goes in Infrastructure:
Repositories
EF (Core)
DbContext
Web API
Clients
File System
Accessors
Email/SMS
Sending
Logging
Adapters
System Clock
Other
Services
Cached
Repositories
Interfaces
Applying Clean Architecture to ASP.NET Core | @ardalis
The Web Project
All dependencies on out-of-process resources.
What Goes in Web:
Controllers Views
ViewModels
Filters Binders
Other Services
Razor
Pages
ApiModels BindingModels
Tag/Html
Helpers
Or
Interfaces
Applying Clean Architecture to ASP.NET Core | @ardalis
Sharing Between Solutions:
Shared Kernel
Common Types May Be Shared Between Solutions. Will be referenced by Core project(s).
Ideally distributed as Nuget Packages.
What Goes in Shared Kernel:
Base Entity
Base Domain
Event
Base
Specification
Common
Exceptions
Common
Interfaces
Common Auth
e.g. User class
Common DI
Common
Logging
Common
Guard Clauses
Applying Clean Architecture to ASP.NET Core | @ardalis
Guard Clauses?
BAD EXAMPLE
public void ProcessOrder(Order order, Custom customer)
{
if(order != null)
{
if(customer != null)
{
// process order here
} else {
throw new ArgumentNullException(nameof(customer), customer);
}
} else {
throw new ArgumentNullException(nameof(order), order);
}
}
Applying Clean Architecture to ASP.NET Core | @ardalis
Guard Clauses?
public void ProcessOrder(Order order, Customer customer)
{
if(order == null) throw new ArgumentNullException(nameof(order),
order);
if(customer==null) throw new ArgumentNullException(nameof(customer),
customer);
// process order here
}
Applying Clean Architecture to ASP.NET Core | @ardalis
Guard Clauses?
Simple checks for input that use common rules and exceptions.
Nuget Package: Ardalis.GuardClauses (https://github.com/ardalis/GuardClauses)
Example:
public void ProcessOrder(Order order, Customer customer)
{
Guard.Against.Null(order, nameof(order));
Guard.Against.Null(customer, nameof(customer));
// process order here
}
Applying Clean Architecture to ASP.NET Core | @ardalis
Solution Structure – Clean Architecture
Web
Core
Infrastructure
Shared Kernel
Unit Tests
Functional
Tests
Integration
Tests
Applying Clean Architecture to ASP.NET Core | @ardalis
Typical (Basic) Folder Structure
Applying Clean Architecture to ASP.NET Core | @ardalis
What belongs in actions/handlers?
Controller Actions (or Page Handlers) should:
1) Accept task-specific types (ViewModel, ApiModel, BindingModel)
2) Perform and handle model validation (ideally w/filters)
3) “Do Work” (More on this in a moment)
4) Create any model type required for response (ViewModel,
ApiModel, etc.)
5) Return an appropriate Result type (View, Page, Ok, NotFound,
etc.)
Applying Clean Architecture to ASP.NET Core | @ardalis
“Do Work” – Option One
Repositories and Entities
1) Get entity from an injected Repository
2) Work with the entity and its methods.
3) Update the entity’s state using the Repository
Great for simple operations
Great for CRUD work
Requires mapping between web models and domain model within controller
Applying Clean Architecture to ASP.NET Core | @ardalis
Applying Clean Architecture to ASP.NET Core | @ardalis
“Do Work” – Option Two
Work with an application service.
1) Pass ApiModel types to service
2) Service internally works with repositories and domain model types.
3) Service returns a web model type
Better for more complex operations
Application Service is responsible for mapping between models
Keeps controllers lightweight, and with fewer injected dependencies
Applying Clean Architecture to ASP.NET Core | @ardalis
Applying Clean Architecture to ASP.NET Core | @ardalis
“Do Work” – Option Three
Work with commands and a tool like Mediatr
1) Use ApiModel types that represent commands (e.g. RegisterUser)
2) Send model-bound instance of command to handler using
_mediator.Send()
No need to inject separate services to different controllers – Mediatr becomes
only dependency.
Applying Clean Architecture to ASP.NET Core | @ardalis
Instantiate Appropriate Command
Applying Clean Architecture to ASP.NET Core | @ardalis
Resolve Command w/Model Binding
Applying Clean Architecture to ASP.NET Core | @ardalis
Code Walkthrough
GITHUB.COM/ARDALIS/CLEANARCHITECTURE
Applying Clean Architecture to ASP.NET Core | @ardalis
Resources
Clean Architecture Solution Template
https://github.com/ardalis/cleanarchitecture
For Worker Services: https://github.com/ardalis/CleanArchitecture.WorkerService
Online Courses (Pluralsight and DevIQ)
• SOLID Principles of OO Design https://ardalis.com/ps-stevesmith
• N-Tier Architecture in C# https://ardalis.com/ps-stevesmith
• DDD Fundamentals https://ardalis.com/ps-stevesmith
• ASP.NET Core Quick Start http://aspnetcorequickstart.com/
Weekly Dev Tips Podcast http://www.weeklydevtips.com/
Microsoft Architecture eBook/sample http://aka.ms/WebAppArchitecture
Group Coaching for Developers https://devbetter.com/
Applying Clean Architecture to ASP.NET Core | @ardalis
Thanks!
Steve Smith
steve@ardalis.com
@ardalis
Applying Clean Architecture to ASP.NET Core | @ardalis

Contenu connexe

Tendances

Tendances (20)

Architectural runway
Architectural runwayArchitectural runway
Architectural runway
 
Clean Architecture Essentials - Stockholm Software Craftsmanship
Clean Architecture Essentials - Stockholm Software CraftsmanshipClean Architecture Essentials - Stockholm Software Craftsmanship
Clean Architecture Essentials - Stockholm Software Craftsmanship
 
Design patterns for microservice architecture
Design patterns for microservice architectureDesign patterns for microservice architecture
Design patterns for microservice architecture
 
Domain Driven Design
Domain Driven DesignDomain Driven Design
Domain Driven Design
 
Microservices Design Patterns
Microservices Design PatternsMicroservices Design Patterns
Microservices Design Patterns
 
How to choose between SharePoint lists, SQL Azure, Microsoft Dataverse with D...
How to choose between SharePoint lists, SQL Azure, Microsoft Dataverse with D...How to choose between SharePoint lists, SQL Azure, Microsoft Dataverse with D...
How to choose between SharePoint lists, SQL Azure, Microsoft Dataverse with D...
 
Microservices Part 3 Service Mesh and Kafka
Microservices Part 3 Service Mesh and KafkaMicroservices Part 3 Service Mesh and Kafka
Microservices Part 3 Service Mesh and Kafka
 
Elastic-Engineering
Elastic-EngineeringElastic-Engineering
Elastic-Engineering
 
Domain Driven Design: Zero to Hero
Domain Driven Design: Zero to HeroDomain Driven Design: Zero to Hero
Domain Driven Design: Zero to Hero
 
Introduction to microservices
Introduction to microservicesIntroduction to microservices
Introduction to microservices
 
Microservices Architecture & Testing Strategies
Microservices Architecture & Testing StrategiesMicroservices Architecture & Testing Strategies
Microservices Architecture & Testing Strategies
 
Microservices Design Patterns | Edureka
Microservices Design Patterns | EdurekaMicroservices Design Patterns | Edureka
Microservices Design Patterns | Edureka
 
Domain Driven Design (DDD)
Domain Driven Design (DDD)Domain Driven Design (DDD)
Domain Driven Design (DDD)
 
Domain Driven Design
Domain Driven Design Domain Driven Design
Domain Driven Design
 
Domain Driven Design
Domain Driven DesignDomain Driven Design
Domain Driven Design
 
Microservices Architecture Part 2 Event Sourcing and Saga
Microservices Architecture Part 2 Event Sourcing and SagaMicroservices Architecture Part 2 Event Sourcing and Saga
Microservices Architecture Part 2 Event Sourcing and Saga
 
Domain driven design
Domain driven designDomain driven design
Domain driven design
 
Domain Driven Design
Domain Driven DesignDomain Driven Design
Domain Driven Design
 
Microservices Architecture - Cloud Native Apps
Microservices Architecture - Cloud Native AppsMicroservices Architecture - Cloud Native Apps
Microservices Architecture - Cloud Native Apps
 
Introduction to Microservices
Introduction to MicroservicesIntroduction to Microservices
Introduction to Microservices
 

Similaire à Clean architecture with asp.net core by Ardalis

App Connect v12. Unit testing with a Pipeline Example. Trevor Dolby Architect...
App Connect v12. Unit testing with a Pipeline Example. Trevor Dolby Architect...App Connect v12. Unit testing with a Pipeline Example. Trevor Dolby Architect...
App Connect v12. Unit testing with a Pipeline Example. Trevor Dolby Architect...
mrle7
 
2005 - .NET SummerCamp: Web developmentwith IIS & ASP.NET webservices
2005 - .NET SummerCamp: Web developmentwith IIS & ASP.NET webservices2005 - .NET SummerCamp: Web developmentwith IIS & ASP.NET webservices
2005 - .NET SummerCamp: Web developmentwith IIS & ASP.NET webservices
Daniel Fisher
 

Similaire à Clean architecture with asp.net core by Ardalis (20)

Asp.NETZERO - A Workshop Presentation by Citytech Software
Asp.NETZERO - A Workshop Presentation by Citytech SoftwareAsp.NETZERO - A Workshop Presentation by Citytech Software
Asp.NETZERO - A Workshop Presentation by Citytech Software
 
Onion Architecture with S#arp
Onion Architecture with S#arpOnion Architecture with S#arp
Onion Architecture with S#arp
 
Unboxing ASP.NET Core
Unboxing ASP.NET CoreUnboxing ASP.NET Core
Unboxing ASP.NET Core
 
Data Agility for Devops - OSI 2018
Data Agility for Devops - OSI 2018Data Agility for Devops - OSI 2018
Data Agility for Devops - OSI 2018
 
SoCal DevOps Meetup 1/26/2017 - Habitat by Chef
SoCal DevOps Meetup 1/26/2017 - Habitat by ChefSoCal DevOps Meetup 1/26/2017 - Habitat by Chef
SoCal DevOps Meetup 1/26/2017 - Habitat by Chef
 
.NET Core, ASP.NET Core Course, Session 6
.NET Core, ASP.NET Core Course, Session 6.NET Core, ASP.NET Core Course, Session 6
.NET Core, ASP.NET Core Course, Session 6
 
ASP.NET Presentation
ASP.NET PresentationASP.NET Presentation
ASP.NET Presentation
 
ArchiMate application and data architecture layer - Simplify the models
ArchiMate application and data architecture layer - Simplify the modelsArchiMate application and data architecture layer - Simplify the models
ArchiMate application and data architecture layer - Simplify the models
 
Unlock-the-Power-of-ASPNET-Core-development
Unlock-the-Power-of-ASPNET-Core-developmentUnlock-the-Power-of-ASPNET-Core-development
Unlock-the-Power-of-ASPNET-Core-development
 
App Connect v12. Unit testing with a Pipeline Example. Trevor Dolby Architect...
App Connect v12. Unit testing with a Pipeline Example. Trevor Dolby Architect...App Connect v12. Unit testing with a Pipeline Example. Trevor Dolby Architect...
App Connect v12. Unit testing with a Pipeline Example. Trevor Dolby Architect...
 
Clean architecture
Clean architectureClean architecture
Clean architecture
 
Enabling Fast IT using Containers, Microservices and DAVROS models: an overview
Enabling Fast IT using Containers, Microservices and DAVROS models: an overviewEnabling Fast IT using Containers, Microservices and DAVROS models: an overview
Enabling Fast IT using Containers, Microservices and DAVROS models: an overview
 
Leveraging HybridMultiCloud for Devops and Automation Platform
Leveraging HybridMultiCloud for Devops and Automation PlatformLeveraging HybridMultiCloud for Devops and Automation Platform
Leveraging HybridMultiCloud for Devops and Automation Platform
 
Move Your .NET Apps to AWS Without Betting the House - WIN303 - re:Invent 2017
Move Your .NET Apps to AWS Without Betting the House - WIN303 - re:Invent 2017Move Your .NET Apps to AWS Without Betting the House - WIN303 - re:Invent 2017
Move Your .NET Apps to AWS Without Betting the House - WIN303 - re:Invent 2017
 
2005 - .NET SummerCamp: Web developmentwith IIS & ASP.NET webservices
2005 - .NET SummerCamp: Web developmentwith IIS & ASP.NET webservices2005 - .NET SummerCamp: Web developmentwith IIS & ASP.NET webservices
2005 - .NET SummerCamp: Web developmentwith IIS & ASP.NET webservices
 
Onion (clean) architecture
Onion (clean) architectureOnion (clean) architecture
Onion (clean) architecture
 
Application Deployment Patterns in the Cloud - NOVA Cloud and Software Engine...
Application Deployment Patterns in the Cloud - NOVA Cloud and Software Engine...Application Deployment Patterns in the Cloud - NOVA Cloud and Software Engine...
Application Deployment Patterns in the Cloud - NOVA Cloud and Software Engine...
 
Twelve Factor - Designing for Change
Twelve Factor - Designing for ChangeTwelve Factor - Designing for Change
Twelve Factor - Designing for Change
 
Building cloud native apps
Building cloud native appsBuilding cloud native apps
Building cloud native apps
 
Clean Infrastructure as Code
Clean Infrastructure as Code Clean Infrastructure as Code
Clean Infrastructure as Code
 

Plus de Steven Smith

Plus de Steven Smith (20)

Finding Patterns in the Clouds - Cloud Design Patterns
Finding Patterns in the Clouds - Cloud Design PatternsFinding Patterns in the Clouds - Cloud Design Patterns
Finding Patterns in the Clouds - Cloud Design Patterns
 
Introducing domain driven design - dogfood con 2018
Introducing domain driven design - dogfood con 2018Introducing domain driven design - dogfood con 2018
Introducing domain driven design - dogfood con 2018
 
Design Pattern Mastery - Momentum Dev Con 19 Apr 2018
Design Pattern Mastery - Momentum Dev Con 19 Apr 2018Design Pattern Mastery - Momentum Dev Con 19 Apr 2018
Design Pattern Mastery - Momentum Dev Con 19 Apr 2018
 
Introducing Domain Driven Design - codemash
Introducing Domain Driven Design - codemashIntroducing Domain Driven Design - codemash
Introducing Domain Driven Design - codemash
 
Most Useful Design Patterns
Most Useful Design PatternsMost Useful Design Patterns
Most Useful Design Patterns
 
Improving the Design of Existing Software
Improving the Design of Existing SoftwareImproving the Design of Existing Software
Improving the Design of Existing Software
 
Introducing ASP.NET Core 2.0
Introducing ASP.NET Core 2.0Introducing ASP.NET Core 2.0
Introducing ASP.NET Core 2.0
 
Decoupling with Domain Events
Decoupling with Domain EventsDecoupling with Domain Events
Decoupling with Domain Events
 
Improving the Quality of Existing Software
Improving the Quality of Existing SoftwareImproving the Quality of Existing Software
Improving the Quality of Existing Software
 
Improving the Quality of Existing Software
Improving the Quality of Existing SoftwareImproving the Quality of Existing Software
Improving the Quality of Existing Software
 
Breaking Dependencies to Allow Unit Testing - DevIntersection Spring 2016
Breaking Dependencies to Allow Unit Testing - DevIntersection Spring 2016Breaking Dependencies to Allow Unit Testing - DevIntersection Spring 2016
Breaking Dependencies to Allow Unit Testing - DevIntersection Spring 2016
 
Improving the Quality of Existing Software - DevIntersection April 2016
Improving the Quality of Existing Software - DevIntersection April 2016Improving the Quality of Existing Software - DevIntersection April 2016
Improving the Quality of Existing Software - DevIntersection April 2016
 
Breaking Dependencies to Allow Unit Testing
Breaking Dependencies to Allow Unit TestingBreaking Dependencies to Allow Unit Testing
Breaking Dependencies to Allow Unit Testing
 
Improving the Quality of Existing Software
Improving the Quality of Existing SoftwareImproving the Quality of Existing Software
Improving the Quality of Existing Software
 
A Whirldwind Tour of ASP.NET 5
A Whirldwind Tour of ASP.NET 5A Whirldwind Tour of ASP.NET 5
A Whirldwind Tour of ASP.NET 5
 
Domain events
Domain eventsDomain events
Domain events
 
My Iraq Experience
My Iraq ExperienceMy Iraq Experience
My Iraq Experience
 
Add Some DDD to Your ASP.NET MVC, OK?
Add Some DDD to Your ASP.NET MVC, OK?Add Some DDD to Your ASP.NET MVC, OK?
Add Some DDD to Your ASP.NET MVC, OK?
 
Domain-Driven Design with ASP.NET MVC
Domain-Driven Design with ASP.NET MVCDomain-Driven Design with ASP.NET MVC
Domain-Driven Design with ASP.NET MVC
 
Breaking Dependencies to Allow Unit Testing
Breaking Dependencies to Allow Unit TestingBreaking Dependencies to Allow Unit Testing
Breaking Dependencies to Allow Unit Testing
 

Dernier

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Dernier (20)

Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source Milvus
 

Clean architecture with asp.net core by Ardalis

  • 1. Applying Clean Architecture to ASP.NET Core Apps STEVE SMITH ARDALIS.COM | @ARDALIS | STEVE@ARDALIS.COM MENTOR | TRAINER | COACH | FORCE MULTIPLIER Applying Clean Architecture to ASP.NET Core | @ardalis
  • 2. Welcome SLC-NET Folks! Applying Clean Architecture to ASP.NET Core | @ardalis
  • 3. Literally 10 minutes before starting… Applying Clean Architecture to ASP.NET Core | @ardalis
  • 4. Literally 10 minutes before starting… Applying Clean Architecture to ASP.NET Core | @ardalis
  • 5. Learn More After Today 1) Pluralsight – FREE in April 2020 ◦ Domain-Driven Design Fundamentals https://www.pluralsight.com/courses/domain-driven-design-fundamentals 2) Microsoft FREE eBook/Sample App (updated for .NET Core 3.1) ◦ eShopOnWeb eCommerce Sample https://ardalis.com/architecture-ebook 3) Contact me for mentoring/training for your company/team 4) Developer Career Mentoring at devBetter.com Applying Clean Architecture to ASP.NET Core | @ardalis
  • 6. Weekly Dev Tips Podcast and Newsletter (and stream)  Ardalis.com/tips  WeeklyDevTips.com Streaming at twitch.tv/ardalis Fridays Applying Clean Architecture to ASP.NET Core | @ardalis
  • 7. Questions HOPEFULLY YOU’LL KNOW THE ANSWERS WHEN WE’RE DONE Applying Clean Architecture to ASP.NET Core | @ardalis
  • 8. Why do we separate applications into multiple projects? Applying Clean Architecture to ASP.NET Core | @ardalis
  • 9. What are some principles we can apply when organizing our software modules? Applying Clean Architecture to ASP.NET Core | @ardalis
  • 10. How does the organization of our application’s solution impact coupling? Applying Clean Architecture to ASP.NET Core | @ardalis
  • 11. What problems result from certain common approaches? Applying Clean Architecture to ASP.NET Core | @ardalis
  • 12. How does Clean Architecture address these problems? Applying Clean Architecture to ASP.NET Core | @ardalis
  • 13. How does ASP.NET Core help? Applying Clean Architecture to ASP.NET Core | @ardalis
  • 15.
  • 16. Separation of Concerns Avoid mixing different code responsibilities in the same (method | class | project) Applying Clean Architecture to ASP.NET Core | @ardalis
  • 17. Separation of Concerns The Big Three™ Data Access Business Rules and Domain Model User Interface Applying Clean Architecture to ASP.NET Core | @ardalis
  • 18. Applying Clean Architecture to ASP.NET Core | @ardalis
  • 19. Single Responsibility Works in tandem with Separation of Concerns Classes should focus on a single responsibility – a single reason to change. Applying Clean Architecture to ASP.NET Core | @ardalis
  • 20. Applying Clean Architecture to ASP.NET Core | @ardalis
  • 21. Following Don’t Repeat Yourself… Refactor repetitive code into functions Group functions into cohesive classes Group classes into folders and namespaces by  Responsibility  Level of abstraction  Etc. Further group class folders into projects Applying Clean Architecture to ASP.NET Core | @ardalis
  • 22. Applying Clean Architecture to ASP.NET Core | @ardalis
  • 23. Invert (and inject) Dependencies Both high level classes and implementation-detail classes should depend on abstractions (interfaces). Applying Clean Architecture to ASP.NET Core | @ardalis
  • 24. Invert (and inject) Dependencies Classes should follow Explicit Dependencies Principle: Request all dependencies via their constructor Make your types honest, not deceptive Applying Clean Architecture to ASP.NET Core | @ardalis
  • 25. Invert (and inject) Dependencies Corollary: Abstractions/interfaces must be defined somewhere accessible by: Low level implementation services High level business services User interface entry points Applying Clean Architecture to ASP.NET Core | @ardalis
  • 26. Applying Clean Architecture to ASP.NET Core | @ardalis
  • 27. Applying Clean Architecture to ASP.NET Core | @ardalis
  • 28. Make the right thing easy and the wrong thing hard FORCE DEVELOPERS INTO A “PIT OF SUCCESS” Applying Clean Architecture to ASP.NET Core | @ardalis
  • 29. Applying Clean Architecture to ASP.NET Core | @ardalis
  • 30. Make the right thing easy and the wrong thing hard. UI classes shouldn’t depend directly on infrastructure classes ◦ How can we structure our solution to help enforce this? Applying Clean Architecture to ASP.NET Core | @ardalis
  • 31. Make the right thing easy and the wrong thing hard. Business/domain classes shouldn’t depend on infrastructure classes ◦ How can our solution design help? Applying Clean Architecture to ASP.NET Core | @ardalis
  • 32. Make the right thing easy and the wrong thing hard. Repetition of (query logic, validation logic, policies, error handling, anything) is a problem ◦ What patterns can we apply to make avoiding repetition easier than copy/pasting? Applying Clean Architecture to ASP.NET Core | @ardalis
  • 33. “Classic” N-Tier Architecture OR N-LAYER Layer Layer Layer Applying Clean Architecture to ASP.NET Core | @ardalis
  • 34. Source: MSDN Website, 2001 Applying Clean Architecture to ASP.NET Core | @ardalis
  • 35. Transitive Dependencies DB Data Access Layer Business Logic Layer User Interface Layer Everything Depends on the database Applying Clean Architecture to ASP.NET Core | @ardalis
  • 36. Applying Clean Architecture to ASP.NET Core | @ardalis
  • 37. Domain-Centric Design AND THE CLEAN ARCHITECTURE Core Business Logic Everything Else Applying Clean Architecture to ASP.NET Core | @ardalis
  • 38. Domain Model Not just business logic, but also: A model of the problem space composed of Entities, Interfaces, Services, and more. Interfaces define contracts for working with domain objects Everything in the application (including infrastructure and data access) depends on these interfaces and domain objects Applying Clean Architecture to ASP.NET Core | @ardalis
  • 39. Clean Architecture Onion Architecture Hexagonal Architecture Ports and Adapters Applying Clean Architecture to ASP.NET Core | @ardalis
  • 40. Applying Clean Architecture to ASP.NET Core | @ardalis
  • 41. Applying Clean Architecture to ASP.NET Core | @ardalis
  • 42. Clean Architecture “Rules” 1. You do not talk about Clean Architecture. Applying Clean Architecture to ASP.NET Core | @ardalis
  • 43. Clean Architecture “Rules” 1. You do not talk about Clean Architecture. Applying Clean Architecture to ASP.NET Core | @ardalis
  • 44. Clean Architecture “Rules” The Application Core contains the Domain Model Applying Clean Architecture to ASP.NET Core | @ardalis
  • 45. Clean Architecture “Rules” All projects depend on the Core project; dependencies point inward toward this core Applying Clean Architecture to ASP.NET Core | @ardalis
  • 46. Clean Architecture “Rules” Inner projects define interfaces; Outer projects implement them Applying Clean Architecture to ASP.NET Core | @ardalis
  • 47. Clean Architecture “Rules” Avoid direct dependency on the Infrastructure project (except from Integration Tests and possibly Startup.cs) Applying Clean Architecture to ASP.NET Core | @ardalis
  • 48. Clean Architecture Features Framework Independent ◦ You can use this architecture with ASP.NET (Core), Java, Python, etc. ◦ It doesn’t rely on any software library or proprietary codebase. Applying Clean Architecture to ASP.NET Core | @ardalis
  • 49. Clean Architecture Features Database Independent ◦ The vast majority of the code has no knowledge of persistence details. ◦ This knowledge may exist in just one class, in one project that no other project references. Applying Clean Architecture to ASP.NET Core | @ardalis
  • 50. Clean Architecture Features UI Independent ◦ Only the UI project cares about the UI. ◦ The rest of the system is UI-agnostic. Applying Clean Architecture to ASP.NET Core | @ardalis
  • 51. Clean Architecture Features Testable ◦ Apps built using this approach, and especially the core domain model and its business rules, are easy to test. Applying Clean Architecture to ASP.NET Core | @ardalis
  • 52. Refactoring to a Clean Architecture Best to start from a properly organized solution ◦ See https://github.com/ardalis/CleanArchitecture Next-best: Start from an application consisting of just a single project Most difficult: Large, existing investment in multi-layer architecture without abstractions or DI Applying Clean Architecture to ASP.NET Core | @ardalis
  • 53. The Core Project (domain model) Minimal dependencies – none on Infrastructure. What Goes in Core: Interfaces Entities Value Objects Aggregates Domain Services Domain Events Exceptions Specifications Event Handlers Applying Clean Architecture to ASP.NET Core | @ardalis
  • 54. The Infrastructure Project All dependencies on out-of-process resources. What Goes in Infrastructure: Repositories EF (Core) DbContext Web API Clients File System Accessors Email/SMS Sending Logging Adapters System Clock Other Services Cached Repositories Interfaces Applying Clean Architecture to ASP.NET Core | @ardalis
  • 55. The Web Project All dependencies on out-of-process resources. What Goes in Web: Controllers Views ViewModels Filters Binders Other Services Razor Pages ApiModels BindingModels Tag/Html Helpers Or Interfaces Applying Clean Architecture to ASP.NET Core | @ardalis
  • 56. Sharing Between Solutions: Shared Kernel Common Types May Be Shared Between Solutions. Will be referenced by Core project(s). Ideally distributed as Nuget Packages. What Goes in Shared Kernel: Base Entity Base Domain Event Base Specification Common Exceptions Common Interfaces Common Auth e.g. User class Common DI Common Logging Common Guard Clauses Applying Clean Architecture to ASP.NET Core | @ardalis
  • 57. Guard Clauses? BAD EXAMPLE public void ProcessOrder(Order order, Custom customer) { if(order != null) { if(customer != null) { // process order here } else { throw new ArgumentNullException(nameof(customer), customer); } } else { throw new ArgumentNullException(nameof(order), order); } } Applying Clean Architecture to ASP.NET Core | @ardalis
  • 58. Guard Clauses? public void ProcessOrder(Order order, Customer customer) { if(order == null) throw new ArgumentNullException(nameof(order), order); if(customer==null) throw new ArgumentNullException(nameof(customer), customer); // process order here } Applying Clean Architecture to ASP.NET Core | @ardalis
  • 59. Guard Clauses? Simple checks for input that use common rules and exceptions. Nuget Package: Ardalis.GuardClauses (https://github.com/ardalis/GuardClauses) Example: public void ProcessOrder(Order order, Customer customer) { Guard.Against.Null(order, nameof(order)); Guard.Against.Null(customer, nameof(customer)); // process order here } Applying Clean Architecture to ASP.NET Core | @ardalis
  • 60. Solution Structure – Clean Architecture Web Core Infrastructure Shared Kernel Unit Tests Functional Tests Integration Tests Applying Clean Architecture to ASP.NET Core | @ardalis
  • 61. Typical (Basic) Folder Structure Applying Clean Architecture to ASP.NET Core | @ardalis
  • 62. What belongs in actions/handlers? Controller Actions (or Page Handlers) should: 1) Accept task-specific types (ViewModel, ApiModel, BindingModel) 2) Perform and handle model validation (ideally w/filters) 3) “Do Work” (More on this in a moment) 4) Create any model type required for response (ViewModel, ApiModel, etc.) 5) Return an appropriate Result type (View, Page, Ok, NotFound, etc.) Applying Clean Architecture to ASP.NET Core | @ardalis
  • 63. “Do Work” – Option One Repositories and Entities 1) Get entity from an injected Repository 2) Work with the entity and its methods. 3) Update the entity’s state using the Repository Great for simple operations Great for CRUD work Requires mapping between web models and domain model within controller Applying Clean Architecture to ASP.NET Core | @ardalis
  • 64. Applying Clean Architecture to ASP.NET Core | @ardalis
  • 65. “Do Work” – Option Two Work with an application service. 1) Pass ApiModel types to service 2) Service internally works with repositories and domain model types. 3) Service returns a web model type Better for more complex operations Application Service is responsible for mapping between models Keeps controllers lightweight, and with fewer injected dependencies Applying Clean Architecture to ASP.NET Core | @ardalis
  • 66. Applying Clean Architecture to ASP.NET Core | @ardalis
  • 67. “Do Work” – Option Three Work with commands and a tool like Mediatr 1) Use ApiModel types that represent commands (e.g. RegisterUser) 2) Send model-bound instance of command to handler using _mediator.Send() No need to inject separate services to different controllers – Mediatr becomes only dependency. Applying Clean Architecture to ASP.NET Core | @ardalis
  • 68. Instantiate Appropriate Command Applying Clean Architecture to ASP.NET Core | @ardalis
  • 69. Resolve Command w/Model Binding Applying Clean Architecture to ASP.NET Core | @ardalis
  • 71. Resources Clean Architecture Solution Template https://github.com/ardalis/cleanarchitecture For Worker Services: https://github.com/ardalis/CleanArchitecture.WorkerService Online Courses (Pluralsight and DevIQ) • SOLID Principles of OO Design https://ardalis.com/ps-stevesmith • N-Tier Architecture in C# https://ardalis.com/ps-stevesmith • DDD Fundamentals https://ardalis.com/ps-stevesmith • ASP.NET Core Quick Start http://aspnetcorequickstart.com/ Weekly Dev Tips Podcast http://www.weeklydevtips.com/ Microsoft Architecture eBook/sample http://aka.ms/WebAppArchitecture Group Coaching for Developers https://devbetter.com/ Applying Clean Architecture to ASP.NET Core | @ardalis
  • 72. Thanks! Steve Smith steve@ardalis.com @ardalis Applying Clean Architecture to ASP.NET Core | @ardalis

Notes de l'éditeur

  1. Photo by Rodrigo Soares on Unsplash
  2. Otherwise they’re likely to end up in …
  3. Working on such systems, with all of their tight coupling, can be draining…
  4. Often worthwhile to split tests into separate projects by type. Can make it easier to run certain sets of tests based on context/environment.