Book Image

Practical Microservices with Dapr and .NET - Second Edition

By : Davide Bedin
Book Image

Practical Microservices with Dapr and .NET - Second Edition

By: Davide Bedin

Overview of this book

This second edition will help you get to grips with microservice architectures and how to manage application complexities with Dapr in no time. You'll understand how Dapr simplifies development while allowing you to work with multiple languages and platforms. Following a C# sample, you'll understand how Dapr's runtime, building blocks, and software development kits (SDKs) help you to simplify the creation of resilient and portable microservices. Dapr provides an event-driven runtime that supports the essential features you need for building microservices, including service invocation, state management, and publish/subscribe messaging. You'll explore all of those in addition to various other advanced features with this practical guide to learning Dapr. With a focus on deploying the Dapr sample application to an Azure Kubernetes Service cluster and to the Azure Container Apps serverless platform, you’ll see how to expose the Dapr application with NGINX, YARP, and Azure API Management. By the end of this book, you'll be able to write microservices easily by implementing industry best practices to solve problems related to distributed systems.
Table of Contents (20 chapters)
1
Part 1: Introduction to Dapr
5
Part 2: Building Microservices with Dapr
11
Part 3: Deploying and Scaling Dapr Solutions

Building our first Dapr sample

It is time to see Dapr in action. We are going to build a web API that returns a hello world message. We chose to base all our samples in the C:\Repos\practical-dapr\ folder, and we created a C:\Repos\practical-dapr\chapter01 folder for this first sample. We’ll take the following steps:

  1. Let’s start by creating a Web API ASP.NET project as follows:
    PS C:\Repos\practical-dapr\chapter01> dotnet new webapi
    -o dapr.microservice.webapi
  2. Then, we add the reference to the Dapr SDK for ASP.NET. The current version is 1.5.0. You can look for the package versions on NuGet at https://www.nuget.org/packages/Dapr.Actors.AspNetCore with the dotnet add package command, as illustrated in the following code snippet:
    PS C:\Repos\practical-dapr\chapter01> dotnet add package
    Dapr.AspNetCore --version 1.8.0
  3. We need to apply some changes to the template we used to create the project. These are going to be much easier to do via VS Code—with the <directory>\code . command, we open it in the scope of the project folder.
  4. To support Dapr in ASP.NET 6 and leverage minimal hosting and global usings, we made a few changes to the code in Program.cs. We changed the builder.Services.AddControllers() method to builder.Services.AddControllers().AddDapr().

We also added app.MapSubscribeHandler(). While this is not necessary for our sample, as we will not use the pub/sub features of Dapr, it is better to have it in mind as the base set of changes you need to apply to a default ASP.NET project.

Finally, in order to simplify the code, we commented app.UseHttpsRedirection().

The following is the modified code of the Program.cs class:

var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers().AddDapr();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}
//app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.MapSubscribeHandler();
app.Run();

In the preceding code block, we instructed Dapr to leverage the Model-View-Controller (MVC) pattern in ASP.NET 6.

  1. Finally, we added a controller named HelloWorldController as illustrated in the following code snippet:
    using Microsoft.AspNetCore.Mvc;
    namespace dapr.microservice.webapi.Controllers;
    [ApiController]
    [Route("[controller]")]
    public class HelloController : ControllerBase
    {
        private readonly ILogger<HelloController> _logger;
        public HelloController(ILogger<HelloController>
          logger)
        {
            _logger = logger;
        }
        [HttpGet()]
        public ActionResult<string> Get()
        {
            Console.WriteLine("Hello, World.");
            return "Hello, World";
        }
    }

In the preceding code snippet, you can see [Route] and [HttpGet]. These ASP.NET attributes are evaluated by the routing to identify the method name.

  1. In order to run a Dapr application, you use the following command structure:
    dapr run --app-id <your app id> --app-port <port of the 
    application> --dapr-http-port <port in Dapr> dotnet run

We left the ASP.NET default port as 5000 but we changed the Dapr HTTP port to 5010. The following command line launches the Dapr application:

PS C:\Repos\practical-dapr\chapter01\dapr.microservice.
webapi> dapr run --app-id hello-world --app-port 5000
--dapr-http-port 5010 dotnet run
Starting Dapr with id hello-world. HTTP Port: 5010. gRPC
Port: 52443

The initial message informs you that Dapr is going to use port 5010 for HTTP as specified, while for gRPC, it is going to auto-select an available port.

The log from Dapr is full of information. To confirm your application is running correctly in the context of the Dapr runtime, you can look for the following code:

Updating metadata for app command: dotnet run
You're up and running! Both Dapr and your app logs will
appear here.

At this stage, ASP.NET is responding locally on port 5000 and Dapr is responding on port 5010. In order to test Dapr, let’s invoke a curl command as follows, and using the browser is equally fine:

PS C:\Repos\practical-dapr\chapter01> curl http://
localhost:5010/v1.0/invoke/hello-world/method/hello
Hello, World

This exciting response has been returned by Dapr, which passed our (the client’s) initial request to the ASP.NET Web API framework. You should also see that the same result logged as Console.WriteLine sends its output to the Dapr window as follows:

== APP == Hello, World.
  1. From another window, let’s verify our Dapr service details. Instead of using the dapr list command, let’s open the Dapr dashboard as follows:
    PS C:\Windows\System32> dapr dashboard
    Dapr Dashboard running on http://localhost:8080

We can open the dashboard by navigating to http://localhost:8080 to reveal the following screen:

Figure 1.3 – Dapr dashboard application

Figure 1.3 – Dapr dashboard application

The Dapr dashboard shown in Figure 1.3 illustrates the details of our hello-world application.

In this case, the Dapr dashboard shows only this sample application we are running on the development machine. In a Kubernetes environment, it would show all the microservices running, along with the other components.

The Dapr dashboard also displays the configured components in the hosting environment, as we can see in the following screenshot:

Figure 1.4 – Dapr dashboard components

Figure 1.4 – Dapr dashboard components

In Figure 1.4, the Dapr dashboard shows us that the local installation of Redis is configured as state store and pub/sub components, in addition to the deployment of Zipkin.

This ends our introductory section, where we were able to build our first Dapr sample.