SlideShare ist ein Scribd-Unternehmen logo
1 von 65
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
Learn More After Today
1) Pluralsight
◦ N-Tier Apps with C# https://www.pluralsight.com/courses/n-tier-apps-part1
◦ Domain-Driven Design Fundamentals https://www.pluralsight.com/courses/domain-driven-design-fundamentals
2) DevIQ
◦ ASP.NET Core Quick Start https://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
◦ Developer Career Mentoring at devBetter.com
Applying Clean Architecture to ASP.NET Core | @ardalis
Weekly Dev Tips
Podcast and Newsletter
 Ardalis.com/tips
 WeeklyDevTips.com
(I have stickers if you’re into that)
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
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
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
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
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?
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
}
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
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

Weitere ähnliche Inhalte

Mehr von Steven Smith

Decoupling with Domain Events
Decoupling with Domain EventsDecoupling with Domain Events
Decoupling with Domain EventsSteven Smith
 
Improving the Quality of Existing Software
Improving the Quality of Existing SoftwareImproving the Quality of Existing Software
Improving the Quality of Existing SoftwareSteven Smith
 
Improving the Quality of Existing Software
Improving the Quality of Existing SoftwareImproving the Quality of Existing Software
Improving the Quality of Existing SoftwareSteven Smith
 
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 2016Steven Smith
 
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 2016Steven Smith
 
Breaking Dependencies to Allow Unit Testing
Breaking Dependencies to Allow Unit TestingBreaking Dependencies to Allow Unit Testing
Breaking Dependencies to Allow Unit TestingSteven Smith
 
Improving the Quality of Existing Software
Improving the Quality of Existing SoftwareImproving the Quality of Existing Software
Improving the Quality of Existing SoftwareSteven Smith
 
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 5Steven Smith
 
My Iraq Experience
My Iraq ExperienceMy Iraq Experience
My Iraq ExperienceSteven Smith
 
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?Steven Smith
 
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 MVCSteven Smith
 
Breaking Dependencies to Allow Unit Testing
Breaking Dependencies to Allow Unit TestingBreaking Dependencies to Allow Unit Testing
Breaking Dependencies to Allow Unit TestingSteven Smith
 
Improving The Quality of Existing Software
Improving The Quality of Existing SoftwareImproving The Quality of Existing Software
Improving The Quality of Existing SoftwareSteven Smith
 
Refactoring with SOLID Principles (FalafelCon 2013)
Refactoring with SOLID Principles (FalafelCon 2013)Refactoring with SOLID Principles (FalafelCon 2013)
Refactoring with SOLID Principles (FalafelCon 2013)Steven Smith
 
Common ASP.NET Design Patterns - Telerik India DevCon 2013
Common ASP.NET Design Patterns - Telerik India DevCon 2013Common ASP.NET Design Patterns - Telerik India DevCon 2013
Common ASP.NET Design Patterns - Telerik India DevCon 2013Steven Smith
 
Refactoring with SOLID - Telerik India DevCon 2013
Refactoring with SOLID - Telerik India DevCon 2013Refactoring with SOLID - Telerik India DevCon 2013
Refactoring with SOLID - Telerik India DevCon 2013Steven Smith
 
Refactoring Applications using SOLID Principles
Refactoring Applications using SOLID PrinciplesRefactoring Applications using SOLID Principles
Refactoring Applications using SOLID PrinciplesSteven Smith
 
Common asp.net design patterns aspconf2012
Common asp.net design patterns aspconf2012Common asp.net design patterns aspconf2012
Common asp.net design patterns aspconf2012Steven Smith
 
Common design patterns (migang 16 May 2012)
Common design patterns (migang 16 May 2012)Common design patterns (migang 16 May 2012)
Common design patterns (migang 16 May 2012)Steven Smith
 

Mehr von Steven Smith (20)

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
 
Improving The Quality of Existing Software
Improving The Quality of Existing SoftwareImproving The Quality of Existing Software
Improving The Quality of Existing Software
 
Refactoring with SOLID Principles (FalafelCon 2013)
Refactoring with SOLID Principles (FalafelCon 2013)Refactoring with SOLID Principles (FalafelCon 2013)
Refactoring with SOLID Principles (FalafelCon 2013)
 
Common ASP.NET Design Patterns - Telerik India DevCon 2013
Common ASP.NET Design Patterns - Telerik India DevCon 2013Common ASP.NET Design Patterns - Telerik India DevCon 2013
Common ASP.NET Design Patterns - Telerik India DevCon 2013
 
Refactoring with SOLID - Telerik India DevCon 2013
Refactoring with SOLID - Telerik India DevCon 2013Refactoring with SOLID - Telerik India DevCon 2013
Refactoring with SOLID - Telerik India DevCon 2013
 
Refactoring Applications using SOLID Principles
Refactoring Applications using SOLID PrinciplesRefactoring Applications using SOLID Principles
Refactoring Applications using SOLID Principles
 
Common asp.net design patterns aspconf2012
Common asp.net design patterns aspconf2012Common asp.net design patterns aspconf2012
Common asp.net design patterns aspconf2012
 
Common design patterns (migang 16 May 2012)
Common design patterns (migang 16 May 2012)Common design patterns (migang 16 May 2012)
Common design patterns (migang 16 May 2012)
 

Kürzlich hochgeladen

"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 

Kürzlich hochgeladen (20)

"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 

Clean architecture with ASP.NET Core

  • 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. Learn More After Today 1) Pluralsight ◦ N-Tier Apps with C# https://www.pluralsight.com/courses/n-tier-apps-part1 ◦ Domain-Driven Design Fundamentals https://www.pluralsight.com/courses/domain-driven-design-fundamentals 2) DevIQ ◦ ASP.NET Core Quick Start https://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 ◦ Developer Career Mentoring at devBetter.com Applying Clean Architecture to ASP.NET Core | @ardalis
  • 3. Weekly Dev Tips Podcast and Newsletter  Ardalis.com/tips  WeeklyDevTips.com (I have stickers if you’re into that) Streaming at twitch.tv/ardalis Fridays Applying Clean Architecture to ASP.NET Core | @ardalis
  • 4. Questions HOPEFULLY YOU’LL KNOW THE ANSWERS WHEN WE’RE DONE Applying Clean Architecture to ASP.NET Core | @ardalis
  • 5. Why do we separate applications into multiple projects? Applying Clean Architecture to ASP.NET Core | @ardalis
  • 6. What are some principles we can apply when organizing our software modules? Applying Clean Architecture to ASP.NET Core | @ardalis
  • 7. How does the organization of our application’s solution impact coupling? Applying Clean Architecture to ASP.NET Core | @ardalis
  • 8. What problems result from certain common approaches? Applying Clean Architecture to ASP.NET Core | @ardalis
  • 9. How does Clean Architecture address these problems? Applying Clean Architecture to ASP.NET Core | @ardalis
  • 10. How does ASP.NET Core help? Applying Clean Architecture to ASP.NET Core | @ardalis
  • 12.
  • 13. Separation of Concerns Avoid mixing different code responsibilities in the same (method | class | project) Applying Clean Architecture to ASP.NET Core | @ardalis
  • 14. Separation of Concerns The Big Three™ Data Access Business Rules and Domain Model User Interface Applying Clean Architecture to ASP.NET Core | @ardalis
  • 15.
  • 16. 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
  • 17.
  • 18. 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
  • 19. Applying Clean Architecture to ASP.NET Core | @ardalis
  • 20. 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
  • 21. 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
  • 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 Applying Clean Architecture to ASP.NET Core | @ardalis
  • 23. Applying Clean Architecture to ASP.NET Core | @ardalis
  • 24. Applying Clean Architecture to ASP.NET Core | @ardalis
  • 25. 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
  • 26. 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
  • 27. 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
  • 28. 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
  • 29. “Classic” N-Tier Architecture OR N-LAYER Layer Layer Layer Applying Clean Architecture to ASP.NET Core | @ardalis
  • 30. Source: MSDN Website, 2001 Applying Clean Architecture to ASP.NET Core | @ardalis
  • 31. 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
  • 32. Domain-Centric Design AND THE CLEAN ARCHITECTURE Core Business Logic Everything Else Applying Clean Architecture to ASP.NET Core | @ardalis
  • 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 Applying Clean Architecture to ASP.NET Core | @ardalis
  • 34. Clean Architecture Onion Architecture Hexagonal Architecture Ports and Adapters Applying Clean Architecture to ASP.NET Core | @ardalis
  • 35. Applying Clean Architecture to ASP.NET Core | @ardalis
  • 36. Applying Clean Architecture to ASP.NET Core | @ardalis
  • 37. Clean Architecture “Rules” 1. You do not talk about Clean Architecture. Applying Clean Architecture to ASP.NET Core | @ardalis
  • 38. Clean Architecture “Rules” 1. You do not talk about Clean Architecture. Applying Clean Architecture to ASP.NET Core | @ardalis
  • 39. Clean Architecture “Rules” The Application Core contains the Domain Model Applying Clean Architecture to ASP.NET Core | @ardalis
  • 40. Clean Architecture “Rules” All projects depend on the Core project; dependencies point inward toward this core Applying Clean Architecture to ASP.NET Core | @ardalis
  • 41. Clean Architecture “Rules” Inner projects define interfaces; Outer projects implement them Applying Clean Architecture to ASP.NET Core | @ardalis
  • 42. 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
  • 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. Applying Clean Architecture to ASP.NET Core | @ardalis
  • 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. Applying Clean Architecture to ASP.NET Core | @ardalis
  • 45. 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
  • 46. 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
  • 47. 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
  • 48. 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
  • 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 Applying Clean Architecture to ASP.NET Core | @ardalis
  • 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 Applying Clean Architecture to ASP.NET Core | @ardalis
  • 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 Applying Clean Architecture to ASP.NET Core | @ardalis
  • 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 } Applying Clean Architecture to ASP.NET Core | @ardalis
  • 53. Solution Structure – Clean Architecture Web Core Infrastructure Shared Kernel Unit Tests Functional Tests Integration Tests Applying Clean Architecture to ASP.NET Core | @ardalis
  • 54. Typical (Basic) Folder Structure Applying Clean Architecture to ASP.NET Core | @ardalis
  • 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.) Applying Clean Architecture to ASP.NET Core | @ardalis
  • 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 Applying Clean Architecture to ASP.NET Core | @ardalis
  • 57. Applying Clean Architecture to ASP.NET Core | @ardalis
  • 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 models Keeps controllers lightweight, and with fewer injected dependencies Applying Clean Architecture to ASP.NET Core | @ardalis
  • 59. Applying Clean Architecture to ASP.NET Core | @ardalis
  • 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. Applying Clean Architecture to ASP.NET Core | @ardalis
  • 61. Instantiate Appropriate Command Applying Clean Architecture to ASP.NET Core | @ardalis
  • 62. Resolve Command w/Model Binding Applying Clean Architecture to ASP.NET Core | @ardalis
  • 64. Resources Clean Architecture Solution Template https://github.com/ardalis/cleanarchitecture 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
  • 65. Thanks! Steve Smith steve@ardalis.com @ardalis Applying Clean Architecture to ASP.NET Core | @ardalis

Hinweis der Redaktion

  1. Photo by Rodrigo Soares on Unsplash
  2. Often worthwhile to split tests into separate projects by type. Can make it easier to run certain sets of tests based on context/environment.