Cover....1
Copyright....3
Contributors....6
Table of Contents....10
Preface....28
Section 1: Principles and Methodologies....36
Chapter 1: Introduction....38
What is a design pattern?....39
Anti-patterns and code smells....40
Anti-patterns....40
Anti-pattern: God class....41
Code smells....41
Code smell: Control Freak....41
Code smell: long methods....42
Understanding the web: request/response....42
Getting started with .NET....46
.NET SDK versus runtime....47
.NET 5+ versus .NET Standard....47
The command-line interface versus Visual Studio Code versus Visual Studio....48
An overview of project templates....48
Running and building your program....49
Technical requirements....50
Summary....50
Questions....51
Further reading....51
Answers....51
Chapter 2: Automated Testing....54
An overview of automated testing....54
Unit testing....57
Integration testing....58
End-to-end testing....58
Other types of tests....58
Finding the right balance....59
Enhancing code quality....62
Improving quality with refactoring....62
Managing technical debt....63
Testing approaches....64
TDD....64
ATDD....64
BDD....65
Testing techniques....66
White-box testing....66
Black-box testing....66
Gray-box testing....67
White-box vs. black-box vs. gray-box testing....67
Conclusion....68
Test case creation....69
Equivalence partitioning....69
Boundary value analysis....70
Decision table testing....70
State transition testing....71
Use case testing....71
Introducing the xUnit framework....72
How to create an xUnit test project....72
Key xUnit features....73
FactAttribute....73
Assertions....76
TheoryAttribute....78
Fixture....88
Arrange, Act, Assert....89
Organizing your tests....90
Unit tests....91
Namespaces....91
Test class names....92
Test code inside the test class....93
Integration tests....94
Writing ASP.NET Core integration tests....94
Classic web application....95
Minimal hosting....98
Workaround....98
Alternative to using fixtures....100
Creating a reusable test application....101
Important testing principles....102
Summary....103
Questions....103
Further reading....103
Answers....104
Chapter 3: Architectural Principles....106
Separation of concerns (SoC)....106
Don’t repeat yourself (DRY)....107
Keep it simple, stupid (KISS)....109
You Aren’t Gonna Need It (YAGNI)....110
The SOLID principles....110
Single responsibility principle (SRP)....110
Project – Single Responsibility....111
Open/closed principle (OCP)....113
Project – Open Close....114
Liskov substitution principle (LSP)....117
The LSP explained....117
Covariance and contravariance....119
Project – Liskov Substitution....122
Conclusion....127
Interface segregation principle (ISP)....128
What is an interface?....128
Project – Interface Segregation....129
Conclusion....134
Dependency inversion principle (DIP)....135
Direct dependency....135
Inverted dependency....136
Direct subsystems dependency....137
Inverted subsystems dependency....137
Project – Dependency inversion....138
Conclusion....141
Summary....142
Questions....142
Further reading....143
Answers....143
Learn more on Discord....143
Chapter 4: REST APIs....144
REST and HTTP....145
HTTP methods....145
HTTP status codes....146
HTTP headers....147
Versioning....149
Default versioning strategy....149
Versioning strategy....150
Wrapping up....150
The Data Transfer Object (DTO) pattern....151
Goal....151
Design....151
Conceptual examples....152
Registering for an activity....153
Fetching activity registration details....154
Conclusion....155
API contracts....156
Code-first API contract....158
The first endpoint....159
The second endpoint....162
Wrapping up....164
Summary....165
Questions....166
Further reading....166
Answers....166
Section 2: Designing with ASP.NET Core....168
Chapter 5: Minimal APIs....170
Top-level statements....170
Minimal hosting....171
Minimal APIs....172
Mapping a route to a delegate....173
Configuring endpoints....174
Inputs....175
Outputs....182
Metadata....189
Configuring JSON serialization....194
Leveraging endpoint filters....197
Leveraging the endpoint filter factory....200
Organizing endpoints....202
MapGroup....203
Creating a custom Map extension method....204
Class libraries....206
Using Minimal APIs with Data Transfer Objects....207
Goal....208
Design....208
Project – Minimal API....209
Raw CRUD endpoints....210
DTO-enabled endpoints....211
Conclusion....216
Summary....217
Questions....217
Further reading....218
Answers....218
Chapter 6: Model-View-Controller....220
The MVC design pattern....220
Goal....222
Design....222
Anatomy of ASP.NET Core web APIs....223
The entry point....223
Directory structure....224
Controller....224
Returning values....225
Attribute routing....229
Conclusion....232
Using MVC with DTOs....232
Goal....232
Design....233
Project – MVC API....233
Raw CRUD controller....234
DTO controller....235
Conclusion....237
Summary....237
Questions....237
Further reading....238
Answers....238
Chapter 7: Strategy, Abstract Factory, and Singleton Design Patterns....240
The Strategy design pattern....240
Goal....241
Design....241
Project – Strategy....242
Conclusion....247
The Abstract Factory design pattern....248
Goal....248
Design....248
Project – Abstract Factory....250
Project – the mid-range vehicle factory....253
Impacts of the Abstract Factory....254
Conclusion....255
The Singleton design pattern....256
Goal....256
Design....257
An alternative (better) way....259
Code smell – Ambient Context....260
Conclusion....262
Summary....263
Questions....264
Answers....264
Chapter 8: Dependency Injection....266
What is dependency injection?....266
The composition root....270
Striving for adaptability....270
Understanding the use of the IoC container....271
The role of an IoC container....271
Code smell – Control Freak....272
Stable dependencies....273
Volatile dependencies....273
Conclusion....273
Object lifetime....274
What’s an object’s lifetime? ....274
.NET object lifetime....274
Registering our dependencies....278
Registering your features elegantly....278
Project – Registering the demo feature....280
Using external IoC containers....281
Revisiting the Strategy pattern....283
Constructor injection....283
Property injection....283
Method injection....284
Project – Strategy....287
Shared building blocks....287
Control Freak controllers....289
Injecting an implementation in the controllers....290
Injecting an abstraction in the controller....292
Constructing the InjectAbstractionLocationsController....293
Conclusion....297
Revisiting the Singleton pattern....298
Project – Application state....298
First implementation....300
Second implementation....301
Using the implementations....302
Project – Wishlist....305
Conclusion....311
Understanding guard clauses....311
Understanding the Service Locator pattern....312
Project – ServiceLocator....313
Implementing method injection....315
Implementing constructor injection....316
Implementing a minimal API....316
Conclusion....317
Revisiting the Factory pattern....318
Project – Factory....318
Summary....320
Questions....321
Further reading....321
Answers....321
Chapter 9: Application Configuration and the Options Pattern....324
Loading the configuration....325
Learning the options interfaces....326
IOptionsMonitor....327
IOptionsFactory....328
IOptionsSnapshot....328
IOptions....329
Exploring common usage scenarios....329
Manual configuration....329
Using the settings file....330
Injecting options....330
Named options....331
IOptionsFactory....332
IOptionsMonitor....333
IOptionsSnapshot....334
Bind options to an existing object....334
Reloading options at runtime....335
Learning options configuration....337
Creating the program....338
Configuring the options....340
Implementing a configurator object....340
Adding post-configuration....342
Using multiple configurator objects....344
Exploring other configuration possibilities....345
Validating our options objects....347
Eager validation....348
Data annotations....348
Validation types....351
Validating options using FluentValidation....354
Injecting options objects directly ....356
Centralizing the configuration for easier management....359
Using the configuration-binding source generator....362
Using the options validation source generator....363
Using the ValidateOptionsResultBuilder class....366
Wrapping up....368
Summary....369
Questions....370
Further reading....370
Answers....371
Chapter 10: Logging Patterns....372
What is logging?....373
Writing logs....374
Log levels....379
Logging providers....381
Configuring logging....382
Structured logging....385
Summary....386
Questions....387
Further reading....387
Answers....387
Section 3: Component Patterns....388
Chapter 11: Structural Patterns....390
The Decorator design pattern....390
Goal....391
Design....391
Project – Adding behaviors....395
DecoratorA....396
DecoratorB....397
Project – Decorator using Scrutor....398
Conclusion....401
The Composite design pattern....401
Goal....401
Design....402
Project – BookStore....402
Conclusion....414
The Adapter design pattern....414
Goal....414
Design....414
Project – Greeter....416
Conclusion....418
The Façade design pattern....418
Goal....418
Design....419
Project – The façades....421
Opaque façade....421
Transparent façade....424
The program....428
Flexibility in action....431
Alternative façade patterns....433
Conclusion....434
Summary....434
Questions....435
Further reading....435
Answers....435
Chapter 12: Behavioral Patterns....438
The Template Method pattern....438
Goal....438
Design....438
Project – Building a search machine....439
Unit tests....446
Conclusion....449
The Chain of Responsibility pattern....450
Goal....450
Design ....450
Project – Message interpreter....452
Conclusion....458
Mixing the Template Method and Chain of Responsibility patterns....458
Project – Improved message interpreter....459
Project – A final, finer-grained design....461
Conclusion....466
Summary....466
Questions....467
Answers....467
Chapter 13: Operation Result Pattern....470
The Operation Result pattern....470
Goal....471
Design....471
Project – Implementing different Operation Result patterns....473
The Program.cs file....473
The simplest form of the Operation Result pattern....473
A single error message....475
Adding a return value....477
Multiple error messages....478
Adding message severity....480
Sub-classes and factories....485
Project – Registration Application....489
Advantages and disadvantages....494
Advantages....494
Disadvantages....495
Conclusion....495
Summary....495
Questions....496
Further reading....496
Answers....496
Section 4: Application Patterns....498
Anti-pattern – Big Ball of Mud....499
Chapter 14: Layering and Clean Architecture....502
Introducing layering....503
Classic layering model....503
Splitting the layers....506
Layers versus tiers versus assemblies....508
What is a tier?....508
What is a layer?....508
What is an assembly?....509
Responsibilities of the common layers....509
Presentation....509
Domain....509
Rich domain model....510
Anemic domain model....512
The Service layer....513
Data....515
Overview of the Repository pattern....516
Overview of the Unit of Work pattern....518
Abstract layers....520
Sharing the model....523
Clean Architecture....526
Implementing layering in real life....531
To be or not to be a purist?....531
Building a façade over a database....533
Summary....535
Questions....535
Further reading....536
Answers....536
Chapter 15: Object Mappers....538
The Object Mapper pattern....538
Goal....539
Design....539
Project – Mapper....541
Conclusion....546
Code smell – too many dependencies....547
Overview of the Aggregate Services pattern....548
Implementing a mapping façade....554
Implementing a mapping service....557
Exploring AutoMapper....560
Project – AutoMapper....561
Exploring Mapperly....567
Project – Mapperly....567
Summary....571
Questions....572
Further reading....572
Answers....573
Chapter 16: Mediator and CQS Patterns....574
A high-level overview of Vertical Slice Architecture....574
The Mediator pattern....576
Goal....576
Design....576
Project – Mediator (IMediator)....578
Project – Mediator (IChatRoom)....582
Conclusion....587
The CQS pattern....588
Goal....588
Design....589
Project – CQS....590
Conclusion....604
Code smell – Marker Interfaces....605
Metadata....605
Dependency identifier....606
Using MediatR as a mediator....609
Project – Clean Architecture with MediatR....610
Summary....615
Questions....615
Further reading....616
Answers....616
Chapter 17: Getting Started with Vertical Slice Architecture....618
Vertical Slice Architecture....619
What are the advantages and disadvantages?....623
Advantages....623
Disadvantages....623
Downsides or upsides?....624
Project – Vertical Slice Architecture....625
Project organization....626
Exploring a feature....628
Testing....634
Continuing your journey – a few tips and tricks....639
Agile and DevOps synergy....641
Conclusion....642
Summary....643
Questions....644
Further reading....644
Answers....644
Chapter 18: Request-EndPoint-Response (REPR)....646
The Request-EndPoint-Response (REPR) pattern....647
Goal....647
Design....647
Project – SimpleEndpoint....648
Feature: ShuffleText....648
Feature: RandomNumber....650
Feature: UpperCase....651
Conclusion....653
An e-commerce application—a slice of the real-world....654
Assembling our stack....655
Dissecting the code structure....655
Exploring the shopping basket....660
AddItem feature....663
Managing exception handling....668
Creating an exception handler middleware....668
Exception handling using ExceptionMapper....671
Leveraging exceptions to propagate errors....674
Gray-box testing....675
AddItemTest....675
Summary....680
Questions....680
Further reading....680
Answers....680
Chapter 19: Introduction to Microservices Architecture....682
What are microservices?....682
Cohesive unit of business....683
Ownership of data....684
Microservice independence....684
An introduction to Event-Driven Architecture....685
Types of events....686
Domain events....686
Integration events....686
Application events....686
Enterprise events....686
Getting started with message queues....687
Overview of the Publish-Subscribe pattern....689
Message brokers....693
Overview of the Event Sourcing pattern....693
Example....695
Conclusion....703
Introducing Gateway patterns....704
Overview of the Gateway Routing pattern....705
Overview of the Gateway Aggregation pattern....707
Overview of the Backend for Frontend pattern....709
Mixing and matching gateways....710
Conclusion....711
Project – BFF....713
Layering APIs....713
Advantages of a layered API design....714
Disadvantages of a layered API design....715
Running the microservices....715
Manually starting the projects....716
Using Docker Compose to run the projects....717
Briefly testing the services....718
Creating typed HTTP clients using Refit....720
Creating a service that serves the current customer....725
Features....726
Fetching the catalog....726
Fetching the shopping cart....728
Managing the shopping cart....731
Conclusion....735
Revisiting the CQRS pattern....736
Advantages and potential risks....740
Benefits of the CQRS pattern....740
Potential risks of using the CQRS pattern....740
Conclusion....741
Overview of the Microservice Adapter pattern....741
Adapting an existing system to another....742
Decommissioning a legacy application....744
Adapting an event broker to another....750
Conclusion....752
Summary....753
Questions....754
Further reading....754
Answers....755
Chapter 20: Modular Monolith....756
What is a Modular Monolith?....757
What are traditional monoliths?....757
What are microservices?....758
Advantages of Modular Monoliths....758
Key components of a Modular Monolith....758
Implementing a Modular Monolith....760
Planning the project....761
Analyzing the domain....763
Identifying the modules....763
Identifying the interactions between modules....764
Defining our stack....765
The module structure....765
The URI space....767
The data space....768
The message broker....770
Project – Modular Monolith....771
Sending events from the catalog module....771
Consuming the events from the basket module....773
Inside the aggregator....776
Exploring the REST API HttpClient....779
Sending HTTP requests to the API....781
Validating the existence of a product....782
Transitioning to microservices....783
Challenges and pitfalls....784
Summary....785
Questions....786
Further reading....786
Answers....786
An end is simply a new beginning....787
PacktPage....788
Other Books You May Enjoy....790
Index....794
This unique ASP.NET Core book will fill in the gaps in your REST API and backend designs. Learn how to build robust, maintainable, and flexible apps using Gang of Four (GoF) design patterns and modern architectural principles. This new edition is updated for .NET 8 and focuses exclusively on the backend, with new content on REST APIs, the REPR pattern, and building modular monoliths.
You'll start by covering foundational concepts like REST, the SOLID principles, Minimal APIs, dependency injection in .NET, and other ASP.NET Core 8 mechanisms. Then, you'll learn to develop components using design patterns, including many from the GoF. Finally, you'll explore organizing your application code with patterns that vary from layers to feature-oriented vertical slice designs, covering CQS and a deep dive into microservices along the way. A brand-new e-commerce project at the end of the book will tie it all together.
This how-to guide will teach you how to assemble your own APIs from building blocks, to suit whatever real-world requirements you may have.
This book is for intermediate-level ASP.NET Core developers who want to improve their C# app code structure and API design skills. ASP.NET developers who want to modernize their knowledge and enhance their technical architecture skills will also like this book. It's also a good refresher for those in software design roles with more experience looking to update their expertise.
A good knowledge of C# programming and a basic understanding of web concepts is necessary to get the most out of this book, though some refreshers are included along the way.