SlideShare a Scribd company logo
Clean Architecture
with ASP.NET Core
STEVE SMITH
ARDALIS.COM | @ARDALIS | STEVE@DEVIQ.COM
DEVIQ.COM
Learn More After Today
1) Pluralsight
◦ N-Tier Apps with C# http://bit.ly/PS-NTier1
◦ Domain-Driven Design Fundamentals http://bit.ly/ddd-fundamentals
2) DevIQ
◦ ASP.NET Core Quick Start http://aspnetcorequickstart.com
3) Microsoft FREE eBook/Sample App
◦ eShopOnWeb eCommerce Sample https://ardalis.com/architecture-ebook
4) Contact me for mentoring/training for your company/team
Questions
HOPEFULLY YOU’LL KNOW THE ANSWERS WHEN WE’RE DONE
Why do we separate applications into multiple
projects?
What are some principles we can apply when
organizing our software modules?
How does the organization of our application’s
solution impact coupling?
What problems result from certain common
approaches?
How does Clean Architecture address these
problems?
How does ASP.NET Core help?
Principles
A BIT OF GUIDANCE
Separation of Concerns
Avoid mixing different code responsibilities in the
same (method | class | project)
The Big Three™
Data Access
Business Rules and Domain Model
User Interface
Separation of Concerns
The Big Three™
Data Access
Business Rules and Domain Model
User Interface
Single Responsibility
Works in tandem with Separation of Concerns
Classes should focus on a single responsibility – a
single reason to change.
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
More Grouping Options to Explore
Aggregates
Features
Bounded Contexts
Invert (and inject) Dependencies
Both high level classes and implementation-detail classes should
depend on abstractions (interfaces).
Invert (and inject) Dependencies
Classes should follow Explicit Dependencies Principle:
Request all dependencies via their constructor
Make your types honest, not deceptive
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
Make the right thing easy
and the wrong thing hard.
FORCE DEVELOPERS INTO A “PIT OF SUCCESS”
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?
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?
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?
“Classic” N-Tier
Architecture
OR N-LAYER
Layer
Layer
Layer
Source: MSDN Website, 2001
N-Tier Benefits
Code Reuse
Team
Segmentation
Better
Maintainability
(slightly)
Looser
Coupling
N-Tier Drawbacks
Transitive
Dependencies
(some)
Complexity
(still)
Tight
Coupling
Transitive Dependencies
DB
Data Access
Layer
Business Logic
Layer
User Interface
Layer
Everything
Depends on the database
Domain-Centric
Design
AND THE CLEAN ARCHITECTURE
Core
Business
Logic
Everything
Else
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
Clean Architecture
Onion Architecture
Hexagonal Architecture
Ports and Adapters
Clean Architecture “Rules”
1. You do not talk about Clean Architecture.
Clean Architecture “Rules”
1. You do not talk about Clean Architecture.
Clean Architecture “Rules”
The Application Core contains the Domain Model
Clean Architecture “Rules”
All projects depend on the Core project;
dependencies point inward toward this core
Clean Architecture “Rules”
Inner projects define interfaces;
outer projects implement them
Clean Architecture “Rules”
Avoid direct dependency on the Infrastructure project
(except from Integration Tests)
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.
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.
Clean Architecture Features
UI Independent
◦ Only the UI project cares about the UI.
◦ The rest of the system is UI-agnostic.
Clean Architecture Features
Testable
◦ Apps built using this approach, and especially the core domain model and its business rules, are easy to
test.
Refactoring to a Clean Architecture
Best to start from a properly organized solution
◦ See http://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
The Core Project
Minimal dependencies – none on Infrastructure.
What Goes in Core:
Interfaces
Entities Value Objects Aggregates
Domain
Services
Domain Events
Exceptions
Specifications
Event Handlers
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
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
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
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)
{
Guard.Against.Null(order, nameof(order));
// process order here
}
Solution Structure – Clean Architecture
Web
Core
Infrastructure
Shared Kernel
Unit Tests
Functional
Tests
Integration
Tests
Typical (Basic) Folder Structure
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.)
“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
“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 web models and domain model.
Keeps controllers lightweight, and with fewer injected dependencies.
“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.
Instantiate Appropriate Command
Resolve Command w/Model Binding
Code Walkthrough
Resources
Online Courses (Pluralsight and DevIQ)
• SOLID Principles of OO Design http://bit.ly/SOLID-OOP
• N-Tier Architecture in C# http://bit.ly/PS-NTier1 and http://bit.ly/PS-NTier2
• DDD Fundamentals http://bit.ly/ddd-fundamentals
• ASP.NET Core Quick Start http://aspnetcorequickstart.com/
• Weekly Dev Tips Podcast http://www.weeklydevtips.com/
• Microsoft Architecture eBook/sample http://aka.ms/WebAppArchitecture

More Related Content

What's hot

Clean architecture
Clean architectureClean architecture
Clean architectureandbed
 
Hexagonal architecture for java applications
Hexagonal architecture for java applicationsHexagonal architecture for java applications
Hexagonal architecture for java applications
Fabricio Epaminondas
 
SOLID Principles and The Clean Architecture
SOLID Principles and The Clean ArchitectureSOLID Principles and The Clean Architecture
SOLID Principles and The Clean Architecture
Mohamed Galal
 
Learning solid principles using c#
Learning solid principles using c#Learning solid principles using c#
Learning solid principles using c#
Aditya Kumar Rajan
 
Micro-frontend
Micro-frontendMicro-frontend
From Monolithic to Microservices
From Monolithic to Microservices From Monolithic to Microservices
From Monolithic to Microservices
Amazon Web Services
 
Introduction to microservices
Introduction to microservicesIntroduction to microservices
Introduction to microservices
Paulo Gandra de Sousa
 
Domain Driven Design Quickly
Domain Driven Design QuicklyDomain Driven Design Quickly
Domain Driven Design Quickly
Mariam Hakobyan
 
Understanding MicroSERVICE Architecture with Java & Spring Boot
Understanding MicroSERVICE Architecture with Java & Spring BootUnderstanding MicroSERVICE Architecture with Java & Spring Boot
Understanding MicroSERVICE Architecture with Java & Spring Boot
Kashif Ali Siddiqui
 
Microservices Design Patterns Explained | Edureka
Microservices Design Patterns Explained | EdurekaMicroservices Design Patterns Explained | Edureka
Microservices Design Patterns Explained | Edureka
Edureka!
 
DDD Tactical Design with Clean Architecture - Ivan Paulovich
DDD Tactical Design with Clean Architecture - Ivan PaulovichDDD Tactical Design with Clean Architecture - Ivan Paulovich
DDD Tactical Design with Clean Architecture - Ivan Paulovich
Ivan Paulovich
 
Domain Driven Design (DDD)
Domain Driven Design (DDD)Domain Driven Design (DDD)
Domain Driven Design (DDD)
Tom Kocjan
 
Microservice vs. Monolithic Architecture
Microservice vs. Monolithic ArchitectureMicroservice vs. Monolithic Architecture
Microservice vs. Monolithic Architecture
Paul Mooney
 
Clean Architecture Essentials - Stockholm Software Craftsmanship
Clean Architecture Essentials - Stockholm Software CraftsmanshipClean Architecture Essentials - Stockholm Software Craftsmanship
Clean Architecture Essentials - Stockholm Software Craftsmanship
Ivan Paulovich
 
Software architecture patterns
Software architecture patternsSoftware architecture patterns
Software architecture patterns
Md. Sadhan Sarker
 
Microservice architecture
Microservice architectureMicroservice architecture
Microservice architecture
Žilvinas Kuusas
 
Microservice With Spring Boot and Spring Cloud
Microservice With Spring Boot and Spring CloudMicroservice With Spring Boot and Spring Cloud
Microservice With Spring Boot and Spring Cloud
Eberhard Wolff
 
Monoliths and Microservices
Monoliths and Microservices Monoliths and Microservices
Monoliths and Microservices
Bozhidar Bozhanov
 
Microservice Architecture Software Architecture Microservice Design Pattern
Microservice Architecture Software Architecture Microservice Design PatternMicroservice Architecture Software Architecture Microservice Design Pattern
Microservice Architecture Software Architecture Microservice Design Pattern
jeetendra mandal
 
Hexagonal architecture - message-oriented software design
Hexagonal architecture  - message-oriented software designHexagonal architecture  - message-oriented software design
Hexagonal architecture - message-oriented software design
Matthias Noback
 

What's hot (20)

Clean architecture
Clean architectureClean architecture
Clean architecture
 
Hexagonal architecture for java applications
Hexagonal architecture for java applicationsHexagonal architecture for java applications
Hexagonal architecture for java applications
 
SOLID Principles and The Clean Architecture
SOLID Principles and The Clean ArchitectureSOLID Principles and The Clean Architecture
SOLID Principles and The Clean Architecture
 
Learning solid principles using c#
Learning solid principles using c#Learning solid principles using c#
Learning solid principles using c#
 
Micro-frontend
Micro-frontendMicro-frontend
Micro-frontend
 
From Monolithic to Microservices
From Monolithic to Microservices From Monolithic to Microservices
From Monolithic to Microservices
 
Introduction to microservices
Introduction to microservicesIntroduction to microservices
Introduction to microservices
 
Domain Driven Design Quickly
Domain Driven Design QuicklyDomain Driven Design Quickly
Domain Driven Design Quickly
 
Understanding MicroSERVICE Architecture with Java & Spring Boot
Understanding MicroSERVICE Architecture with Java & Spring BootUnderstanding MicroSERVICE Architecture with Java & Spring Boot
Understanding MicroSERVICE Architecture with Java & Spring Boot
 
Microservices Design Patterns Explained | Edureka
Microservices Design Patterns Explained | EdurekaMicroservices Design Patterns Explained | Edureka
Microservices Design Patterns Explained | Edureka
 
DDD Tactical Design with Clean Architecture - Ivan Paulovich
DDD Tactical Design with Clean Architecture - Ivan PaulovichDDD Tactical Design with Clean Architecture - Ivan Paulovich
DDD Tactical Design with Clean Architecture - Ivan Paulovich
 
Domain Driven Design (DDD)
Domain Driven Design (DDD)Domain Driven Design (DDD)
Domain Driven Design (DDD)
 
Microservice vs. Monolithic Architecture
Microservice vs. Monolithic ArchitectureMicroservice vs. Monolithic Architecture
Microservice vs. Monolithic Architecture
 
Clean Architecture Essentials - Stockholm Software Craftsmanship
Clean Architecture Essentials - Stockholm Software CraftsmanshipClean Architecture Essentials - Stockholm Software Craftsmanship
Clean Architecture Essentials - Stockholm Software Craftsmanship
 
Software architecture patterns
Software architecture patternsSoftware architecture patterns
Software architecture patterns
 
Microservice architecture
Microservice architectureMicroservice architecture
Microservice architecture
 
Microservice With Spring Boot and Spring Cloud
Microservice With Spring Boot and Spring CloudMicroservice With Spring Boot and Spring Cloud
Microservice With Spring Boot and Spring Cloud
 
Monoliths and Microservices
Monoliths and Microservices Monoliths and Microservices
Monoliths and Microservices
 
Microservice Architecture Software Architecture Microservice Design Pattern
Microservice Architecture Software Architecture Microservice Design PatternMicroservice Architecture Software Architecture Microservice Design Pattern
Microservice Architecture Software Architecture Microservice Design Pattern
 
Hexagonal architecture - message-oriented software design
Hexagonal architecture  - message-oriented software designHexagonal architecture  - message-oriented software design
Hexagonal architecture - message-oriented software design
 

Similar to Clean architecture with asp.net core

Elements of DDD with ASP.NET MVC & Entity Framework Code First
Elements of DDD with ASP.NET MVC & Entity Framework Code FirstElements of DDD with ASP.NET MVC & Entity Framework Code First
Elements of DDD with ASP.NET MVC & Entity Framework Code First
Enea Gabriel
 
L02 Architecture
L02 ArchitectureL02 Architecture
L02 Architecture
Ólafur Andri Ragnarsson
 
Isset Presentation @ EECI2009
Isset Presentation @ EECI2009Isset Presentation @ EECI2009
Isset Presentation @ EECI2009
Isset Internet Professionals
 
Azure presentation nnug dec 2010
Azure presentation nnug  dec 2010Azure presentation nnug  dec 2010
Azure presentation nnug dec 2010
Ethos Technologies
 
Over view of software artitecture
Over view of software artitectureOver view of software artitecture
Over view of software artitecture
ABDEL RAHMAN KARIM
 
The Magic Of Application Lifecycle Management In Vs Public
The Magic Of Application Lifecycle Management In Vs PublicThe Magic Of Application Lifecycle Management In Vs Public
The Magic Of Application Lifecycle Management In Vs Public
David Solivan
 
Java TechTalk "Spring boot made life easier with Kubernetes and Microservices"
Java TechTalk "Spring boot made life easier with Kubernetes and Microservices"Java TechTalk "Spring boot made life easier with Kubernetes and Microservices"
Java TechTalk "Spring boot made life easier with Kubernetes and Microservices"
GlobalLogic Ukraine
 
Clean architecture with asp.net core by Ardalis
Clean architecture with asp.net core by ArdalisClean architecture with asp.net core by Ardalis
Clean architecture with asp.net core by Ardalis
Steven Smith
 
A Lightweight MDD Process Applied in Small Projects
A Lightweight MDD Process Applied in Small ProjectsA Lightweight MDD Process Applied in Small Projects
A Lightweight MDD Process Applied in Small Projects
Gabor Guta
 
Software Architecture for Agile Development
Software Architecture for Agile DevelopmentSoftware Architecture for Agile Development
Software Architecture for Agile Development
Hayim Makabee
 
Domain Driven Design
Domain Driven DesignDomain Driven Design
Domain Driven Design
Up2 Technology
 
Twelve Factor - Designing for Change
Twelve Factor - Designing for ChangeTwelve Factor - Designing for Change
Twelve Factor - Designing for Change
Eric Wyles
 
Best practices for creating modular Web applications
Best practices for creating modular Web applicationsBest practices for creating modular Web applications
Best practices for creating modular Web applications
peychevi
 
Yemo_Capstone_MS_Fairfield University
Yemo_Capstone_MS_Fairfield UniversityYemo_Capstone_MS_Fairfield University
Yemo_Capstone_MS_Fairfield UniversityGuillermo Julca
 
Gk1051 001 j2-ee_arch_tt425v1.1
Gk1051 001 j2-ee_arch_tt425v1.1Gk1051 001 j2-ee_arch_tt425v1.1
Gk1051 001 j2-ee_arch_tt425v1.1vciampa
 
Dairy management system project report..pdf
Dairy management system project report..pdfDairy management system project report..pdf
Dairy management system project report..pdf
Kamal Acharya
 
Actively looking for an opportunity to work as a challenging Dot Net Developer
Actively looking for an opportunity to work as a challenging Dot Net DeveloperActively looking for an opportunity to work as a challenging Dot Net Developer
Actively looking for an opportunity to work as a challenging Dot Net Developer
Karthik Reddy
 
Actively looking for an opportunity to work as a challenging Dot Net Developer
Actively looking for an opportunity to work as a challenging Dot Net DeveloperActively looking for an opportunity to work as a challenging Dot Net Developer
Actively looking for an opportunity to work as a challenging Dot Net Developer
Karthik Reddy
 
ASAS 2014 - Simon Brown
ASAS 2014 - Simon BrownASAS 2014 - Simon Brown
ASAS 2014 - Simon Brown
Avisi B.V.
 

Similar to Clean architecture with asp.net core (20)

Elements of DDD with ASP.NET MVC & Entity Framework Code First
Elements of DDD with ASP.NET MVC & Entity Framework Code FirstElements of DDD with ASP.NET MVC & Entity Framework Code First
Elements of DDD with ASP.NET MVC & Entity Framework Code First
 
L02 Architecture
L02 ArchitectureL02 Architecture
L02 Architecture
 
Isset Presentation @ EECI2009
Isset Presentation @ EECI2009Isset Presentation @ EECI2009
Isset Presentation @ EECI2009
 
Domain Driven Design
Domain Driven DesignDomain Driven Design
Domain Driven Design
 
Azure presentation nnug dec 2010
Azure presentation nnug  dec 2010Azure presentation nnug  dec 2010
Azure presentation nnug dec 2010
 
Over view of software artitecture
Over view of software artitectureOver view of software artitecture
Over view of software artitecture
 
The Magic Of Application Lifecycle Management In Vs Public
The Magic Of Application Lifecycle Management In Vs PublicThe Magic Of Application Lifecycle Management In Vs Public
The Magic Of Application Lifecycle Management In Vs Public
 
Java TechTalk "Spring boot made life easier with Kubernetes and Microservices"
Java TechTalk "Spring boot made life easier with Kubernetes and Microservices"Java TechTalk "Spring boot made life easier with Kubernetes and Microservices"
Java TechTalk "Spring boot made life easier with Kubernetes and Microservices"
 
Clean architecture with asp.net core by Ardalis
Clean architecture with asp.net core by ArdalisClean architecture with asp.net core by Ardalis
Clean architecture with asp.net core by Ardalis
 
A Lightweight MDD Process Applied in Small Projects
A Lightweight MDD Process Applied in Small ProjectsA Lightweight MDD Process Applied in Small Projects
A Lightweight MDD Process Applied in Small Projects
 
Software Architecture for Agile Development
Software Architecture for Agile DevelopmentSoftware Architecture for Agile Development
Software Architecture for Agile Development
 
Domain Driven Design
Domain Driven DesignDomain Driven Design
Domain Driven Design
 
Twelve Factor - Designing for Change
Twelve Factor - Designing for ChangeTwelve Factor - Designing for Change
Twelve Factor - Designing for Change
 
Best practices for creating modular Web applications
Best practices for creating modular Web applicationsBest practices for creating modular Web applications
Best practices for creating modular Web applications
 
Yemo_Capstone_MS_Fairfield University
Yemo_Capstone_MS_Fairfield UniversityYemo_Capstone_MS_Fairfield University
Yemo_Capstone_MS_Fairfield University
 
Gk1051 001 j2-ee_arch_tt425v1.1
Gk1051 001 j2-ee_arch_tt425v1.1Gk1051 001 j2-ee_arch_tt425v1.1
Gk1051 001 j2-ee_arch_tt425v1.1
 
Dairy management system project report..pdf
Dairy management system project report..pdfDairy management system project report..pdf
Dairy management system project report..pdf
 
Actively looking for an opportunity to work as a challenging Dot Net Developer
Actively looking for an opportunity to work as a challenging Dot Net DeveloperActively looking for an opportunity to work as a challenging Dot Net Developer
Actively looking for an opportunity to work as a challenging Dot Net Developer
 
Actively looking for an opportunity to work as a challenging Dot Net Developer
Actively looking for an opportunity to work as a challenging Dot Net DeveloperActively looking for an opportunity to work as a challenging Dot Net Developer
Actively looking for an opportunity to work as a challenging Dot Net Developer
 
ASAS 2014 - Simon Brown
ASAS 2014 - Simon BrownASAS 2014 - Simon Brown
ASAS 2014 - Simon Brown
 

Recently uploaded

BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024
Ortus Solutions, Corp
 
Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...
Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...
Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...
Hivelance Technology
 
Strategies for Successful Data Migration Tools.pptx
Strategies for Successful Data Migration Tools.pptxStrategies for Successful Data Migration Tools.pptx
Strategies for Successful Data Migration Tools.pptx
varshanayak241
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2
 
Enhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdfEnhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdf
Globus
 
Lecture 1 Introduction to games development
Lecture 1 Introduction to games developmentLecture 1 Introduction to games development
Lecture 1 Introduction to games development
abdulrafaychaudhry
 
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Globus
 
Visitor Management System in India- Vizman.app
Visitor Management System in India- Vizman.appVisitor Management System in India- Vizman.app
Visitor Management System in India- Vizman.app
NaapbooksPrivateLimi
 
GlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote sessionGlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote session
Globus
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke
 
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamOpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
takuyayamamoto1800
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
Max Andersen
 
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisProviding Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Globus
 
Cyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdfCyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdf
Cyanic lab
 
Explore Modern SharePoint Templates for 2024
Explore Modern SharePoint Templates for 2024Explore Modern SharePoint Templates for 2024
Explore Modern SharePoint Templates for 2024
Sharepoint Designs
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Shahin Sheidaei
 
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Globus
 
Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024
Globus
 
Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024
Paco van Beckhoven
 
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns
 

Recently uploaded (20)

BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024
 
Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...
Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...
Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...
 
Strategies for Successful Data Migration Tools.pptx
Strategies for Successful Data Migration Tools.pptxStrategies for Successful Data Migration Tools.pptx
Strategies for Successful Data Migration Tools.pptx
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
 
Enhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdfEnhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdf
 
Lecture 1 Introduction to games development
Lecture 1 Introduction to games developmentLecture 1 Introduction to games development
Lecture 1 Introduction to games development
 
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...
 
Visitor Management System in India- Vizman.app
Visitor Management System in India- Vizman.appVisitor Management System in India- Vizman.app
Visitor Management System in India- Vizman.app
 
GlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote sessionGlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote session
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
 
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamOpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
 
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisProviding Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
 
Cyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdfCyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdf
 
Explore Modern SharePoint Templates for 2024
Explore Modern SharePoint Templates for 2024Explore Modern SharePoint Templates for 2024
Explore Modern SharePoint Templates for 2024
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
 
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
 
Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024
 
Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024
 
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology Solutions
 

Clean architecture with asp.net core

  • 1. Clean Architecture with ASP.NET Core STEVE SMITH ARDALIS.COM | @ARDALIS | STEVE@DEVIQ.COM DEVIQ.COM
  • 2. Learn More After Today 1) Pluralsight ◦ N-Tier Apps with C# http://bit.ly/PS-NTier1 ◦ Domain-Driven Design Fundamentals http://bit.ly/ddd-fundamentals 2) DevIQ ◦ ASP.NET Core Quick Start http://aspnetcorequickstart.com 3) Microsoft FREE eBook/Sample App ◦ eShopOnWeb eCommerce Sample https://ardalis.com/architecture-ebook 4) Contact me for mentoring/training for your company/team
  • 3. Questions HOPEFULLY YOU’LL KNOW THE ANSWERS WHEN WE’RE DONE
  • 4. Why do we separate applications into multiple projects?
  • 5. What are some principles we can apply when organizing our software modules?
  • 6. How does the organization of our application’s solution impact coupling?
  • 7. What problems result from certain common approaches?
  • 8. How does Clean Architecture address these problems?
  • 9. How does ASP.NET Core help?
  • 11.
  • 12. Separation of Concerns Avoid mixing different code responsibilities in the same (method | class | project) The Big Three™ Data Access Business Rules and Domain Model User Interface
  • 13. Separation of Concerns The Big Three™ Data Access Business Rules and Domain Model User Interface
  • 14.
  • 15. Single Responsibility Works in tandem with Separation of Concerns Classes should focus on a single responsibility – a single reason to change.
  • 16.
  • 17. 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
  • 18. More Grouping Options to Explore Aggregates Features Bounded Contexts
  • 19.
  • 20. Invert (and inject) Dependencies Both high level classes and implementation-detail classes should depend on abstractions (interfaces).
  • 21. Invert (and inject) Dependencies Classes should follow Explicit Dependencies Principle: Request all dependencies via their constructor Make your types honest, not deceptive
  • 22. 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
  • 23. Make the right thing easy and the wrong thing hard. FORCE DEVELOPERS INTO A “PIT OF SUCCESS”
  • 24. 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?
  • 25. 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?
  • 26. 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?
  • 31. Transitive Dependencies DB Data Access Layer Business Logic Layer User Interface Layer Everything Depends on the database
  • 32. Domain-Centric Design AND THE CLEAN ARCHITECTURE Core Business Logic Everything Else
  • 33. 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
  • 34. Clean Architecture Onion Architecture Hexagonal Architecture Ports and Adapters
  • 35.
  • 36.
  • 37. Clean Architecture “Rules” 1. You do not talk about Clean Architecture.
  • 38. Clean Architecture “Rules” 1. You do not talk about Clean Architecture.
  • 39. Clean Architecture “Rules” The Application Core contains the Domain Model
  • 40. Clean Architecture “Rules” All projects depend on the Core project; dependencies point inward toward this core
  • 41. Clean Architecture “Rules” Inner projects define interfaces; outer projects implement them
  • 42. Clean Architecture “Rules” Avoid direct dependency on the Infrastructure project (except from Integration Tests)
  • 43. 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.
  • 44. 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.
  • 45. Clean Architecture Features UI Independent ◦ Only the UI project cares about the UI. ◦ The rest of the system is UI-agnostic.
  • 46. Clean Architecture Features Testable ◦ Apps built using this approach, and especially the core domain model and its business rules, are easy to test.
  • 47. Refactoring to a Clean Architecture Best to start from a properly organized solution ◦ See http://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
  • 48. The Core Project Minimal dependencies – none on Infrastructure. What Goes in Core: Interfaces Entities Value Objects Aggregates Domain Services Domain Events Exceptions Specifications Event Handlers
  • 49. 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
  • 50. 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
  • 51. 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
  • 52. 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) { Guard.Against.Null(order, nameof(order)); // process order here }
  • 53. Solution Structure – Clean Architecture Web Core Infrastructure Shared Kernel Unit Tests Functional Tests Integration Tests
  • 55. 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.)
  • 56. “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
  • 57.
  • 58. “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 web models and domain model. Keeps controllers lightweight, and with fewer injected dependencies.
  • 59.
  • 60. “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.
  • 64. Resources Online Courses (Pluralsight and DevIQ) • SOLID Principles of OO Design http://bit.ly/SOLID-OOP • N-Tier Architecture in C# http://bit.ly/PS-NTier1 and http://bit.ly/PS-NTier2 • DDD Fundamentals http://bit.ly/ddd-fundamentals • ASP.NET Core Quick Start http://aspnetcorequickstart.com/ • Weekly Dev Tips Podcast http://www.weeklydevtips.com/ • Microsoft Architecture eBook/sample http://aka.ms/WebAppArchitecture