Book Image

An Atypical ASP.NET Core 6 Design Patterns Guide - Second Edition

By : Carl-Hugo Marcotte
5 (1)
Book Image

An Atypical ASP.NET Core 6 Design Patterns Guide - Second Edition

5 (1)
By: Carl-Hugo Marcotte

Overview of this book

An Atypical ASP.NET Core 6 Design Patterns Guide, Second Edition approaches programming like playing with LEGO®: snapping small pieces together to create something beautiful. Thoroughly updated for ASP.NET Core 6, with further coverage of microservices patterns, data contracts, and event-driven architecture, this book gives you the tools to build and glue reliable components together to improve your programmatic masterpieces. The chapters are organized based on scale and topic, allowing you to start small and build on a strong base, the same way that you would develop a program. You will begin by exploring basic design patterns, SOLID architectural principles, dependency injection, and other ASP.NET Core 6 mechanisms. You will explore component-scale patterns, and then move to higher level application-scale patterns and techniques to better structure your applications. Finally, you'll advance to the client side to connect the dots with tools like Blazor and make ASP.NET Core a viable full-stack web development framework. You will supplement your learning with practical use cases and best practices, exploring a range of significant Gang of Four (GoF) design patterns along the way. By the end of the book, you will be comfortable combining and implementing patterns in different ways, and crafting software solutions of any scale.
Table of Contents (31 chapters)
Preface
Free Chapter
1
Section 1: Principles and Methodologies
5
Section 2: Designing for ASP.NET Core
11
Section 3: Designing at Component Scale
15
Section 4: Designing at Application Scale
21
Section 5: Designing the Client Side
25
Acronyms Lexicon
26
Other Books You May Enjoy
27
Index
Appendices

Preface

Design patterns are a set of solutions to many of the common problems occurring in software development. They are essential for any experienced developer and professionals crafting software solutions of any scale.

We start by exploring basic design patterns, automated testing, the SOLID architectural principles, dependency injection, and other ASP.NET Core mechanisms. Then we explore component-scale patterns oriented toward small chunks of software. Next, we move on to application-scale patterns and techniques, where we explore higher-level patterns and how to structure the application as a whole. The book covers many fundamental Gang of Four (GoF) patterns, such as strategy, singleton, decorator, façade, and composite. The chapters are organized based on scale and topics, allowing you to start small with a strong base and build slowly on top of it, the same way you would build a program. Many use cases in the book combine more than one design pattern to display alternate usage. It also shows that design patterns are tools to be used, not complex concepts to be feared. Finally, we tackle the client side to connect the dots and make ASP.NET Core a viable full stack alternative.

This book is a journey to learn the reasoning behind the craft. By the end of the book, you will be able to mix and match design patterns and will have learned how to think about architecture. You will learn techniques to help you create the building blocks that you need to solve your unique day-to-day design problems.

Who this book is for

The book is intended for intermediate software and web developers with an understanding of .NET who want to write flexible, maintainable, and robust code for building scalable web applications. The book assumes knowledge of C# programming and an understanding of web concepts such as HTTP.

What this book covers

Section 1, Principles and Methodologies

This section contains the book’s foundations: an overview of unit testing and xUnit, the SOLID principles, and some theory and examples on how to design software.

Chapter 1, Introduction, contains the prerequisites and an explanation of how the book works as well as a few important topics that will be useful to a software developer.

Chapter 2, Automated Testing, introduces you to the basics of unit testing and the xUnit testing framework as well as to some good practices and methodologies to help write unit tests.

Chapter 3, Architectural Principles, lays the architectural groundwork with crucial principles used throughout the book and extremely important to any engineer trying to write SOLID code.

Section 2, Designing for ASP.NET Core

This section introduces ASP.NET Core-specific subjects, including Model-View-Controller (MVC), View Models, Data Transfer Objects (DTO), and other classic design patterns. We also deep dive into dependency injection and explore the evolved usage of certain patterns in ASP.NET Core as pillars of modern software engineering.

Chapter 4, The MVC Pattern Using Razor, introduces you to the MVC and the View Model design patterns to render views using Razor and ASP.NET Core MVC.

Chapter 5, The MVC Pattern for Web APIs, takes you further on the ASP.NET Core MVC journey, focusing on web APIs. We explore the DTO pattern and API contracts.

Chapter 6, Understanding the Strategy, Abstract Factory, and Singleton Design Patterns, introduces you to the traditional implementation of three GoF design patterns: Strategy, Abstract Factory, and Singleton.

Chapter 7, Deep Dive into Dependency Injection, takes the ASP.NET Core dependency injection container for a ride, introducing you to one of the most important aspects of modern software development. This chapter connects ASP.NET Core and the SOLID principles. Once the basics of dependency injection are laid out, we review the previous three GoF design patterns and revisit them using dependency injection, opening the way to build testable, flexible, and reliable software.

Chapter 8, Options and Logging Patterns, takes ASP.NET Core-related subjects and digs into them. We cover different options patterns and the abstraction provided to us. We also explore how to leverage logging in .NET 6.

Section 3, Designing at Component Scale

This section focuses on component design, where we study how an individual piece of software can be crafted to achieve a particular goal. We explore a few more GoF patterns that should help you design SOLID data structures and components as well as simplify the complexity of our code by encapsulating our logic in smaller units.

Chapter 9, Structural Patterns, introduces four new GoF structural design patterns and a few variants, such as transparent façades and opaque façades. It also introduces you to Scrutor, an open source project that adds support for the dependency injection of decorators.

Chapter 10, Behavioral Patterns, introduces two GoF behavioral design patterns and concludes by mixing them together as a final improvement on the code sample’s design.

Chapter 11, Understanding the Operation Result Design Pattern, covers multiple variants of the Operation Result design pattern, structuring a result object to carry more than a simple result.

Section 4, Designing at Application Scale

This section takes a step toward application design and introduces layering, vertical slices, and microservices. We overview each technique making sure you know how to get started. We also cover different component-level patterns that help put those architectural styles together.

Chapter 12, Understanding Layering, introduces you to layering and clean architecture, covering the primary objectives behind the presentation, domain, data (persistence) layers, and their clean architecture counterparts, which is the apogee of layering. It also highlights the evolution of application design in the last few decades, helping you understand where it started (the beginning of the chapter) and where it is now (the end of the chapter).

Chapter 13, Getting Started with Object Mappers, covers object mapping (that is, copying an object into another), also known as the Translator pattern, the Mapper pattern, and Entity Translator. The chapter introduces AutoMapper at the end, an open source library, to help us cover the most common scenarios automatically.

Chapter 14, Mediator and CQRS Design Patterns, introduces the Command Query Responsibility Segregation (CQRS) and the Mediator patterns. After covering those two patterns, we explore an open source tool called MediatR, which is foundational to many subsequent subjects.

Chapter 15, Getting Started with Vertical Slice Architecture, introduces Vertical Slice Architecture. It uses a number of the previous patterns and tools that we have explored to piece together a different way to see the design of an application. It also introduces FluentValidation, which gets added to MediatR and AutoMapper.

Chapter 16, Introduction to Microservices Architecture, introduces microservices, what they are, what they are not, and talks about a few related patterns. It introduces many concepts, such as message queues, events, Publish-Subscribe, and Gateway patterns. We also revisit CQRS at cloud scale.

Section 5, Designing the Client Side

This section introduces multiple UI patterns that we can use when developing ASP.NET Core 6 applications, such as Blazor, Razor Pages, and various types of components. It overviews what ASP.NET Core 6 offers in terms of UIs, leading to additional learning paths if you are interested.

Chapter 17, ASP.NET Core User Interfaces, explores most of the UI elements available to us in ASP.NET Core 6, such as Razor Pages, Partial Views, Tag Helpers, View Components, Display Templates, and Editor Templates.

Chapter 18, A Brief Look into Blazor, touches upon Blazor Server quickly, then explores Blazor WebAssembly (Wasm) to complete our journey and transform C#/.NET into a full-stack alternative to other JavaScript technologies. We explore Razor Components and the Model-View-Update design pattern. We end the chapter with a medley of possibilities you can start digging into.

Appendices

The appendices contain additional information about supporting subjects related to the technology used and explored in the book.

Appendix A explores numerous C# features spanning a wide range of versions, including .NET 6 and C# 10. If you don’t understand a piece of code in the book, that feature is most likely covered in Appendix A. Even if you understood all the code, you should find some good tips there.

Appendix B covers additional microservices-related topics like an overview of containers with a cheat sheet-like list of useful Docker commands, an overview of orchestration, and some notions related to scaling applications.

To get the most out of this book

You must know C# and how to program. Boolean logic, loops, and other basic programming constructs should be mastered, including object-oriented programming basics. Some knowledge of ASP.NET will be beneficial. Knowing how to read UML class and sequence diagrams is an asset, but not required.

The code samples and resources are available on GitHub (https://adpg.link/net6). The README.md file at the root of the repository is filled with information to help you find the code and resources you are looking for.

Most links are shortened in the form of https: //adpg.link/**** so readers of a physical copy can easily type URLs quickly.

In the book, I use a mix of Visual Studio 2022 (which has a free version) and Visual Studio Code (free). I recommend that you use one or both of those. The IDE is unrelated to most of the content. You could use Notepad if you are impetuous enough (I don’t recommend that). Unless you install Visual Studio, which comes with the .NET SDK, you may need to install the .NET 6 SDK. The SDK comes with the dotnet CLI as well as the building tools for running and testing your programs. I develop on Windows, but you should be able to use another OS. OS-related topics are very limited, even inexistent. The code compiles on both Windows and Linux.

Download the example code files

The code bundle for the book is hosted on GitHub at https://github.com/PacktPublishing/An-Atypical-ASP.NET-Core-6-Design-Patterns-Guide. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

Download the color images

We also provide a PDF file that has color images of the screenshots/diagrams used in this book. You can download it here: https://static.packt-cdn.com/downloads/9781803249841_ColorImages.pdf.

Conventions used

There are a number of text conventions used throughout this book.

CodeInText: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. For example, “Mount the downloaded WebStorm-10*.dmg disk image file as another disk in your system.”

A block of code is set as follows:

public class FactTest
{
    [Fact]
    public void Should_be_equal()
    {
        var expectedValue = 2;
        var actualValue = 2;
        Assert.Equal(expectedValue, actualValue);
    }
}

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

public class AsyncFactTest
{
    [Fact]
    public async Task Should_be_equal()
    {
        var expectedValue = 2;
        var actualValue = 2;
        await Task.Yield();
        Assert.Equal(expectedValue, actualValue);
    }
}

Any command-line input or output is written as follows:

Passed!  - Failed:     0, Passed:    23, Skipped:     0, Total:    23, Duration: 22 ms - MyApp.Tests.dll (net6.0)

Bold: Indicates a new term, an important word, or words that you see on the screen, for example, in menus or dialog boxes, also appear in the text like this. For example: “Select System info from the Administration panel.”

Warnings or important notes appear like this.

Tips and tricks appear like this.

Get in touch

Feedback from our readers is always welcome.

General feedback: Email [email protected], and mention the book’s title in the subject of your message. If you have questions about any aspect of this book, please email us at [email protected].

Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book we would be grateful if you would report this to us. Please visit, http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details.

Piracy: If you come across any illegal copies of our works in any form on the Internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.

If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit http://authors.packtpub.com.

For more information about Packt, please visit packtpub.com.

Share your thoughts

Once you’ve read An Atypical ASP.NET Core 6 Design Patterns Guide, Second Edition, we’d love to hear your thoughts! Please click here to go straight to the Amazon review page for this book and share your feedback.

Your review is important to us and the tech community and will help us make sure we’re delivering excellent quality content.