title
stringlengths 3
46
| content
stringlengths 0
1.6k
|
---|---|
21:1025 | var queueClient = storageAccount.CreateCloudQueueClient(); |
21:1026 | var messageQueue = queueClient.GetQueueReference(`email`); |
21:1027 | var message = new CloudQueueMessage(requestData); |
21:1028 | await messageQueue.AddMessageAsync(message); |
21:1029 | log.LogInformation(`HTTP trigger from SendEmail function processed a request.`); |
21:1030 | var responseObj = new { success = true }; |
21:1031 | return new HttpResponseMessage(HttpStatusCode.OK) |
21:1032 | { |
21:1033 | Content = new StringContent(JsonConvert.SerializeObject(responseObj), Encoding.UTF8, `application/json`), |
21:1034 | }; |
21:1035 | } |
21:1036 | } |
21:1037 | |
21:1038 | |
21:1039 | In some scenarios, you may try to avoid the queue setup indicated in the preceding code by using a queue output binding. Check out the details at https://docs.microsoft.com/en-us/azure/azure-functions/functions-bindings-storage-queue-output?tabs=csharp. |
21:1040 | |
21:1041 | You can use a tool such as Postman to test your function. Before that, you just need to run the app in Visual Studio, which will launch Azure Functions Core Tools and its emulator: |
21:1042 | |
21:1043 | Figure 21.22: Postman function test |
21:1044 | The result will appear in Microsoft Azure Storage Explorer and the Azure portal. In the Azure portal, you can manage each message and dequeue each of them or even clear the queue storage: |
21:1045 | |
21:1046 | Figure 21.23: HTTP trigger and queue storage test |
21:1047 | To finish this topic, let’s move on to the final third step, where we will create the function that will process the requests for sending emails. |
21:1048 | Third step — creating the queue trigger function |
21:1049 | After this, you can create a second function by right-clicking the project and selecting Add -> New Azure Function. This one will be triggered by data entering your queue. It is worth mentioning that, for Azure Functions v4, you will have the Microsoft.Azure.WebJobs.Extensions.Storage library added as a NuGet reference automatically: |
21:1050 | |
21:1051 | Figure 21.24: Creating a queue trigger |
21:1052 | Once you have set the connection string inside local.settings.json, you will be able to run both functions and test them with Postman. The difference is that, with the second function running, if you set a breakpoint at the start of it, you will be able to check whether the message has been sent: |
21:1053 | |
21:1054 | Figure 21.25: Queue triggered in Visual Studio 2022 |
21:1055 | From this point, the way to send emails will depend on the email options you have. You may decide to use a proxy or connect directly to your email server. |
21:1056 | There are several advantages to creating an email service this way: |
21:1057 | |
21:1058 | Once your service has been coded and tested, you can use it to send emails from any of your applications. This means that your code can always be reused. |
21:1059 | Apps that use this service will not be stopped from sending emails due to the asynchronous advantages of posting in an HTTP service. |
21:1060 | You do not need to pool the queue to check whether data is ready for processing. |
21:1061 | |
21:1062 | Finally, the queue process runs concurrently, which delivers a better experience in most cases. It is possible to turn it off by setting some properties in host.json. All the options for this can be found in the Further reading section at the end of this chapter. |
21:1063 | In this part of the case study, we checked an example of an architecture where you connect multiple functions to avoid pooling data and enable concurrent processing. We have seen with this demo how great the fit between serverless and event-driven architecture is. |
21:1064 | Now, let’s change the subject a bit, and discuss how to implement a frontend microservice. |
21:1065 | A frontend microservice |
21:1066 | In this section, as an example of an ASP.NET Core MVC frontend microservice described in Chapter 18, Implementing Frontend Microservices with ASP.NET Core, we will implement the administrative panel for managing the destinations and packages of the WWTravelClub book use case. The application will be implemented with the DDD approach and associated patterns described in Chapter 7, Understanding the Different Domains in Software Solutions. So, having a good understanding of that chapter is a fundamental prerequisite to reading this chapter. The subsections that follow describe the overall application specifications and organization. The full code of the example can be found in the ch19 folder of the GitHub repository associated with the book. |
21:1067 | As usual, let’s start by stating clearly our frontend microservice specifications. |
21:1068 | Defining application specifications |
21:1069 | The destinations and packages were described in Chapter 13, Interacting with Data in C# – Entity Framework Core. Here, we will use the same data model, with the necessary modifications to adapt it to the DDD approach. The administrative panel must allow packages, a destination listing, and CRUD operations on it. To simplify the application, the two listings will be quite simple: the application will show all destinations sorted according to their names, while all packages will be sorted starting from the ones with a later validity date. |
21:1070 | Furthermore, we make the following assumptions: |
21:1071 | |
21:1072 | The application that shows destinations and packages to the user shares the same database used by the administrative panel. Since only the administrative panel application needs to modify data, there will be just one write copy of the database with several read-only replicas. |
21:1073 | Price modifications and package deletions are immediately used to update the user’s shopping carts. For this reason, the administrative application must send asynchronous communications about price changes and package removals. We will not implement all the communication logic here, but we will just add all such events to an event table, which should be used as input to a parallel thread that’s in charge of sending these events to all relevant microservices. |
21:1074 | |
21:1075 | Here, we will give the full code for just package management; most of the code for destination management is designed as an exercise for you. The full code is available in the ch16 folder of the GitHub repository associated with this book. In the remainder of this section, we will describe the application’s overall organization and discuss some relevant samples of code. We start with an overall description of the application architecture. |
21:1076 | Defining the application architecture |
21:1077 | The application is organized based on the guidelines described in Chapter 7, Understanding the Different Domains in Software Solutions, while considering the DDD approach and related patterns. That is, the application is organized into three layers, each implemented as a different project: |
21:1078 | |
21:1079 | There’s a domain implementation 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 layer DBContext 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. This can be done as follows: |
21:1080 | Right-click on the project icon in Solution Explorer and select Edit project file, or just double-click the project name. |
21:1081 | In the Edit window, add: |
21:1082 | <ItemGroup> |
21:1083 | <FrameworkReference |
21:1084 | Include=`Microsoft.AspNetCore.App` /> |
21:1085 | </ItemGroup> |
21:1086 | |
21:1087 | |
21:1088 | |
21:1089 | |
21:1090 | |
21:1091 | 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. Hence, for instance, the Package entity 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. IPackage has also the associated IPackageRepository repository interface. |
21:1092 | All repository interfaces inherit from the empty IRepository interface. |
21:1093 | |
21:1094 | This way, they declare it as a repository interface, and all repository interfaces can be automatically discovered with reflection and added to the dependency injection engine together with their implementations. |
21:1095 | |
21:1096 | Finally, there’s the application layer – that is, the ASP.NET Core MVC application – 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 (that is, interfaces that inherit from the empty IRepository interface) and IUnitOfWork instances coming from the domain layer to manage and coordinate transactions. |
21:1097 | It is worth pointing out that, in more complex microservices, the application layer may be implemented as a separate library project and would contain just DDD queries, commands, command handlers, and event handlers. While, the MVC project would contain just controllers, UIs, and dependency injection. |
21:1098 | 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. |
21:1099 | 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. |
21:1100 | In any case, it can be beneficial to encapsulate query objects behind interfaces so that their implementations can be replaced by fake implementations when you test controllers. |
21:1101 | 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. |
21:1102 | The following diagram is a sketch of how storage update operations are performed. The circles are data being exchanged between the various layers, while rectangles are the procedures that process them. Moreover, dotted arrows connect interfaces with types that implement them: |
21:1103 | |
21:1104 | Figure 21.26: Diagram of command execution |
21:1105 | Here’s the flow of action through Figure 21.26 as a list of steps: |
21:1106 | |
21:1107 | A controller’s action method receives one or more ViewModels and performs validation. |
21:1108 | 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. |
21:1109 | A command handler matching the previous command is retrieved via Dependency Injection (DI) in the controller action method (through the [FromServices] parameter attribute we described in the Defining controllers and views subsection). Then, the handler is executed. During its execution, the handler interacts with various repository interface methods and with the aggregates they return. |
21:1110 | 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 repository 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 repository interface, 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 repository implementation, and that the whole logic for updating each aggregate is defined in the aggregate itself, not in its associated repository implementation, to keep the code more modular. |
21:1111 | Behind the scenes, in the domain layer implementation, repository 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. |
21:1112 | Domain events are generated during each aggregate process 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. |
21:1113 | The application handles errors by throwing exceptions. |
21:1114 | |
21:1115 | 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. |
21:1116 | |
21:1117 | |
21:1118 | The Visual Studio solution is composed of three projects: |
21:1119 | |
21:1120 | There’s a project containing the domain layer abstraction called PackagesManagementDomain, 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. |
21:1121 | There’s a project containing the whole domain layer implementation called PackagesManagementDB, which is a .NET 8.0 library. |
21:1122 | Finally, there’s an ASP.NET Core MVC 8.0 project called PackagesManagement 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. |
21:1123 | |
21:1124 | Let’s start by creating the PackagesManagement ASP.NET Core MVC project so that the whole solution has the same name as the ASP.NET Core MVC project. Then, we’ll add the other two library projects to the same solution. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.