Book Image

An Atypical ASP.NET Core 5 Design Patterns Guide

By : Carl-Hugo Marcotte
Book Image

An Atypical ASP.NET Core 5 Design Patterns Guide

By: Carl-Hugo Marcotte

Overview of this book

Design patterns are a set of solutions to many of the common problems occurring in software development. Knowledge of these design patterns helps developers and professionals to craft software solutions of any scale. ASP.NET Core 5 Design Patterns starts by exploring basic design patterns, architectural principles, dependency injection, and other ASP.NET Core mechanisms. You’ll explore the component scale as you discover patterns oriented toward small chunks of the software, and then move to application-scale patterns and techniques to understand higher-level patterns and how to structure the application as a whole. The book covers a range of significant GoF (Gangs of Four) design patterns such as strategy, singleton, decorator, facade, and composite. The chapters are organized based on scale and topics, allowing you to start small and build on a strong base, the same way that you would develop a program. With the help of use cases, the book will show you how to combine design patterns to display alternate usage and help you feel comfortable working with a variety of design patterns. Finally, you’ll advance to the client side to connect the dots and make ASP.NET Core a viable full-stack alternative. By the end of the book, you’ll be able to mix and match design patterns and have learned how to think about architecture and how it works.
Table of Contents (27 chapters)
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

Revisiting the Factory pattern

In the Strategy pattern example, we implemented a solution that instantiated a HomePageViewModel using the new keyword. While doing that is acceptable, we could use method injection instead, mixed with the use of a factory. The Factory patterns are handy tools when the time comes to construct objects. Let's take a look at a few rewrites using factories to explore some possibilities.

Factory mixed with method injection

Our first option would be to inject the view model directly into our method instead of injecting IHomeService. To achieve this, let's rewrite the HomeController class like this:

public class HomeController : Controller
{
    public IActionResult Index([FromServices]HomePageViewModel viewModel)
    {
        return View(viewModel);
    }
    // Omitted Privacy() and Error()
}

The FromServicesAttribute class tells the ASP.NET Core pipeline to inject an instance of HomePageViewModel directly into the method.

Now that...