title
stringlengths 3
46
| content
stringlengths 0
1.6k
|
---|---|
18:48 | However, the API gateway offers the opportunity to centralize other functions that are common to all API services, such as: |
18:49 | |
18:50 | Authentication, that is, validating and decoding the authentication token that comes with each request (please do not confuse authentication with login). |
18:51 | Caching, that is, caching responses according to configurable caching policies. |
18:52 | Translation, that is, adapting the interface, as seen by the client, to the actual signature of the various API methods. This way, each API can change its interface without affecting existing clients. |
18:53 | Versioning, that is, directing each request toward a compatible version of each API service. |
18:54 | Documentation, that is, offering a unique documentation endpoint. |
18:55 | |
18:56 | API gateways have continued to evolve, absorbing and offering more and more functions, giving rise to the so-called API management systems that now automate and take care of most of the burden of handling public web APIs. |
18:57 | Azure, like all clouds, offers a good API management service. You can find more information about it here: https://azure.microsoft.com/en-us/services/api-management/#overview. |
18:58 | It is also worth mentioning Ocelot (https://docs.microsoft.com/en-us/dotnet/architecture/microservices/multi-container-microservice-net-applications/implement-api-gateways-ith-ocelot`), a library for easily creating custom API gateways. You can either use it to fill in configuration files or as a base for a completely custom API gateway. |
18:59 | Now, we are ready to discuss HTML micro-frontends, which also add the challenge of combining several HTML fragments into a unique HTML page. |
18:60 | HTML micro-frontends |
18:61 | Several HTML micro-frontends can cooperate on the same application by furnishing each with a different set of web pages. In this case, coordinating them requires nothing more than links pointing to the other micro-frontends and a common sign-in so that users don’t need to log in each time they move to a different micro-frontend. |
18:62 | However, very often, several micro-frontends cooperate in the construction of the same page by supplying various page areas. In this case, a software component must take the burden of assembling the various parts into a unique page. |
18:63 | The main difficulty of combining several HTML fragments into a single HTML page is offering a coherent experience to the user, thus avoiding assembling all page areas in a way that is hard to understand for the user. Another problem is avoiding the continuous page flipping and reorganization each time new content reaches the browser. In what follows, we will discuss how these problems are solved by different technologies. |
18:64 | In the case of classic web applications that build the HTML on the server side, an interface application furnishes the page layout and then calls the various micro-frontends to fill the various layout areas. |
18:65 | |
18:66 | Figure 18.2: Server-side micro-frontend |
18:67 | In this case, there is no browser page flipping and reorganization issue since the whole HTML page is assembled on the server side and sent to the browser only when it is ready. However, we pay for this advantage with the memory consumption for the whole time needed to assemble the whole page before sending it to the browser. |
18:68 | Both the layout to use and which calls to make to the involved micro-frontends are obtained by processing the request URL according to rules that are either hardwired in the code or, better, stored in one or more configuration sources (in the simplest case, a unique configuration file). Using predefined page patterns ensures coherence and a good user experience, but we pay the cost in maintainability because we need to update and test the interface application at each non-trivial change of any single micro-frontend that furnishes page areas. |
18:69 | In the case of SPAs, the assembly process takes place on the client, that is, in the browser: |
18:70 | |
18:71 | A kernel application furnishes the initial HTML page. |
18:72 | The kernel application downloads a JavaScript file from each micro-frontend. Each of these JavaScript files is a micro-SPA that creates page areas. |
18:73 | The kernel application, based on the current URL, decides which URL to pass to each micro-SPA and then puts the HTML produced by each micro-SPA in the right place. |
18:74 | |
18:75 | |
18:76 | Figure 18.3: Client-side micro-frontend |
18:77 | The various micro-SPAs do not interfere with each other because each of them runs in a separate JavaScript scope. Therefore, for instance, we can mix micro-SPAs implemented with different and incompatible versions of Angular and/or React. |
18:78 | Micro-frontends can also be implemented using WebAssembly frameworks like Blazor (see Chapter 19, Client Frameworks: Blazor) that run .NET code. However, in this case, the various micro-SPAs do not run in separate environments, so they must be based on compatible .NET versions. |
18:79 | SPA micro-frontends have the same maintainability costs as server-based micro-frontends and have browser page flipping and reorganization issues since the page is created dynamically as new content and/or data reach the browser. This problem can be solved by pre-allocating each content area of the browser page with fixed-size HTML tags. Thus, for instance, we may pre-allocate a 300 px X 300 px area to show weather forecasts and some pictures or animation while the actual content is loading. |
18:80 | In the next section, we will introduce the architectural schema for building a front-end microservice based on ASP.NET Core MVC. |
18:81 | Defining the application architecture |
18:82 | The application will be implemented with the Domain-Driven Design (DDD) approach and associated patterns described in Chapter 7, Understanding the Different Domains in Software Solutions, and Chapter 13, Interacting with Data in C# – Entity Framework Core, so having a good understanding of the content covered in those chapters is a fundamental prerequisite to reading this chapter. |
18:83 | The application is organized based on a DDD approach and uses SOLID principles to map your domain sections. That is, the application is organized into three layers, each implemented as a different project: |
18:84 | |
18:85 | There’s a domain layer, which contains the repository’s implementation and the classes describing database entities. It is a .NET library project. However, since it needs some interfaces, like IServiceCollection, which are defined in Microsoft.NET.Sdk.web, and since the DBContext layer must inherit from the identity framework in order to also handle the application authentication and authorization database tables, we must add a reference not only to the .NET SDK but also to the ASP.NET Core SDK. However, it is also common to implement custom user management. |
18:86 | There’s also a domain layer abstraction, which contains repository specifications; that is, interfaces that describe repository implementations and DDD aggregates. In our implementation, we decided to implement aggregates by hiding the forbidden operations/properties of root data entities behind interfaces, as discussed in the How data and domain layers communicate with other layers section of Chapter 13, Interacting with Data in C# – Entity Framework Core. Hence, for instance, the Package data layer class, which is an aggregate root, has a corresponding IPackage interface in the domain layer abstraction that hides all the property setters of the Package entity. The domain layer abstraction also contains the definitions of all the domain events, while the event handlers that will subscribe to these events are defined in the application layer. |
18:87 | Finally, there’s the application layer – that is, the ASP.NET Core MVC application (ASP.NET Core MVC is discussed in Chapter 17, Presenting ASP.NET Core) – where we define DDD queries, commands, command handlers, and event handlers. Controllers fill query objects and execute them to get ViewModels they can pass to Views. They update storage by filling command objects and executing their associated command handlers. In turn, command handlers use IRepository interfaces and IUnitOfWork instances coming from the domain layer to manage and coordinate transactions. |
18:88 | |
18:89 | The application uses the Command Query Responsibility Segregation (CQRS) pattern; therefore, it uses command objects to modify the storage and the query object to query it. CQRS was described in the Command Query Responsibility Segregation (CQRS) pattern subsection of Chapter 7, Understanding the Different Domains in Software Solutions. |
18:90 | The query is simple to use and implement: controllers fill their parameters and then call their execution methods. In turn, query objects have direct LINQ implementations that project results directly onto the ViewModels used by the controller Views with Select LINQ methods. You may also decide to hide the LINQ implementation behind the same repository classes used for the storage update operations, but this would turn the definition and modification of simple queries into very time-consuming tasks. |
18:91 | In any case, it could be beneficial to encapsulate query objects behind interfaces so that their implementations can be replaced by fake implementations when you test controllers. |
18:92 | However, the chain of objects and calls involved in the execution of commands is more complex. This is because it requires the construction and modification of aggregates, as well as a definition of the interaction between several aggregates and between aggregates and other applications through domain events to be provided. |
18:93 | The following diagram is a sketch of how storage update operations are performed. The circles are data being exchanged between the various layers, while the rectangles are the procedures that process them. Moreover, dotted arrows connect interfaces with the types that implement them: |
18:94 | |
18:95 | Figure 18.4: Diagram of command execution |
18:96 | Here’s the flow of action through Figure 18.4 as a list of steps: |
18:97 | |
18:98 | A controller’s action method receives one or more ViewModels and performs validation. |
18:99 | One or more ViewModels containing changes to apply are hidden behind interfaces (IMyUpdate) defined in the domain layer. They are used to fill the properties of a command object. These interfaces must be defined in the domain layer since they will be used as arguments of the repository aggregate methods defined there. |
18:100 | A command handler matching the previous command is retrieved via Dependency Injection (DI) in the controller action method. Then, the handler is executed. During its execution, the handler interacts with various repository interface methods and with the aggregates they return. |
18:101 | When creating the command handler discussed in step 3, the ASP.NET Core DI engine automatically injects all parameters declared in its constructor. In particular, it injects all IRepository implementations needed to perform all command handler transactions. The command handler performs its job by calling the methods of these IRepository implementations received in its constructor to build aggregates and modify the built aggregates. Aggregates either represent already-existing entities or newly created ones. Handlers use the IUnitOfWork interface contained in each IRepository, as well as the concurrency exceptions returned by the data layer, to organize their operations as transactions. It is worth pointing out that each aggregate has its own IRepository and that the whole logic for updating each aggregate is defined in the aggregate itself, not in its associated IRepository, to keep the code more modular. |
18:102 | Behind the scenes, in the data layer, IRepository implementations use Entity Framework to perform their job. Aggregates are implemented by root data entities hidden behind interfaces defined in the domain layer, while IUnitOfWork methods, which handle transactions and pass changes to the database, are implemented with DbContext methods. In other words, IUnitOfWork is implemented with the application’s DbContext. |
18:103 | Domain events are generated during each aggregate processing and are added to the aggregates themselves by calling their AddDomainEvent methods. However, they are not triggered immediately. Usually, they are triggered at the end of all the aggregates’ processing and before changes are passed to the database; however, this is not a general rule. |
18:104 | The application handles errors by throwing exceptions. A more efficient approach would be to define a request-scoped object in the dependency engine, where each application subpart may add its errors as domain events. However, while this approach is more efficient, it increases the complexity of the code and the application development time. |
18:105 | |
18:106 | The Visual Studio solution is composed of three projects: |
18:107 | |
18:108 | There’s a project containing the domain layer abstraction, which is a .NET Standard 2.1 library. When a library doesn’t use features or NuGet packages that are specific to a .NET version, it is a good practice to implement it as a .NET Standard library because this way, it doesn’t need modifications when the application is moved to a newer .NET version. |
18:109 | There’s a project containing the whole data layer, which is a .NET 8.0 library based on Entity Framework. |
18:110 | Finally, there’s an ASP.NET Core MVC 8.0 project that contains both the application and presentation layers. When you define this project, select No Authentication; otherwise, the user database will be added directly to the ASP.NET Core MVC project instead of to the database layer. We will add the user database manually in the data layer. |
18:111 | |
18:112 | In the remaining sections, we will describe the implementation of each layer that composes the architecture described so far, starting with domain layer abstraction. |
18:113 | Defining the domain layer interface |
18:114 | Once the PackagesManagementDomain Standard 2.1 library project has been added to the solution, we’ll add a Tools folder to the project root. Then, we’ll place all the DomainLayer tools contained in the code associated with ch7. Since the code contained in this folder uses data annotations and defines DI extension methods, we must also add references to the System.ComponentModel.Annotations and Microsoft.Extensions.DependencyInjection.Abstration NuGet packages. |
18:115 | Then, we need an Aggregates folder containing all the aggregate definitions (which, as already said, we will implement as interfaces). |
18:116 | Below is an example of an aggregate definition: |
18:117 | public interface IPackage : IEntity<int> |
18:118 | { |
18:119 | void FullUpdate(IPackageFullEditDTO packageDTO); |
18:120 | string Name { get; set; } |
18:121 | string Description { get;} |
18:122 | decimal Price { get; set; } |
18:123 | int DurationInDays { get; } |
18:124 | DateTime? StartValidityDate { get;} |
18:125 | DateTime? EndValidityDate { get; } |
18:126 | int DestinationId { get; } |
18:127 | |
18:128 | } |
18:129 | |
18:130 | It contains the same properties as the Package entity, which we saw in Chapter 13, Interacting with Data in C# – Entity Framework Core. The only differences are the following: |
18:131 | |
18:132 | It inherits from IEntity<int>, which furnishes all basic functionalities of aggregates |
18:133 | It has no Id property since it is inherited from IEntity<int> |
18:134 | All properties are read-only, and it has a FullUpdate method since all aggregates can only be modified through update operations defined in the user domain (in our case, the FullUpdate method) |
18:135 | |
18:136 | Now, let’s also add a DTOs folder. Here, we place all interfaces used to pass updates to the aggregates. Such interfaces are implemented by the application layer ViewModels used to define such updates. In our case, it contains IPackageFullEditDTO, which we can use to update existing packages. |
18:137 | An IRepositories folder contains all repository specifications; the following is an example repository interface: |
18:138 | public interface IPackageRepository: |
18:139 | IRepository<IPackage> |
18:140 | { |
18:141 | Task<IPackage> Get(int id); |
18:142 | IPackage New(); |
18:143 | Task<IPackage> Delete(int id); |
18:144 | } |
18:145 | |
18:146 | Repositories always contain just a few methods since all business logic should be represented as aggregate methods – in our case, just the methods to create a new package, retrieve an existing package, and delete an existing package. The logic to modify an existing package is included in the FullUpdate method of IPackage. |
18:147 | Finally, we also have an event folder containing all domain event definitions. We can name this folder Events. Events are triggered whenever a change to an aggregate has consequences either on other aggregates or on other microservices. They are a way to implement weak interactions between aggregates and microservices while keeping the code of aggregates independent of each other. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.