Practical Microservices with Dapr and .NET - Davide Bedin - E-Book

Practical Microservices with Dapr and .NET E-Book

Davide Bedin

0,0
29,99 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

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.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB
MOBI

Seitenzahl: 326

Veröffentlichungsjahr: 2022

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Practical Microservices with Dapr and .NET

A developer's guide to building cloud-native applications using the event-driven runtime

Davide Bedin

BIRMINGHAM—MUMBAI

Practical Microservices with Dapr and .NET

Copyright © 2022 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

Group Product Manager: Gebin George

Publishing Product Manager: Sathyanarayanan Ellapulli

Senior Editor: Rounak Kulkarni

Technical Editor: Pradeep Sahu

Copy Editor: Safis Editing

Project Coordinator: Manisha Singh

Proofreader: Safis Editing

Indexer: Sejal Dsilva

Production Designer: Ponraj Dhandapani

Developer Relations Marketing Executive: Sonakshi Bubbar

First published: June 2019

Second edition: November 2022

Production reference: 1141022

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham

B3 2PB, UK.

ISBN 978-1-80324-812-7

www.packt.com

To my wife Silvia, and my sons, Abramo and Elia: nothing would have been possible without you.

– Davide Bedin

Foreword

It’s been three years since November 2019, when Microsoft launched the initial public release of Dapr, a distributed application runtime, and two years since the first edition of this book was published.

Dapr started as an incubation called Actions in the Azure Office of the CTO in early 2019. Its goal was to simplify the development of distributed microservice-based cloud-native applications. I can say with pride that Dapr is now widely seen as doing just that. It’s a Cloud Native Computing Foundation (CNCF) incubating project and is one of the very few that skipped sandbox stage when accepted to the CNCF. Dapr has over 1000 contributors, over 100 components, is in production at dozens of enterprises, and has even been integrated into cloud-native compute services by multiple cloud providers.

Dapr’s novel innovation is that it implements a growing collection of abstract APIs, called building blocks, that it makes available to applications via a side-car HTTP or gRPC interface. The building blocks include service invocation for microservices to exchange synchronous requests, pub/sub for asynchronous message delivery, state store for saving data, input/output for integrating with external services, secret management, configuration management, and more.

Because applications use Dapr APIs and not service APIs directly, you can plug in a component (which is an implementation of a building block) without changing application code. Using a building block makes code portable across different environments with respect to the building block’s functionality, including across multiple clouds. If you want to deploy code to Azure, for example, you can plug in the Event Hubs component into the pub/sub building block, then swap it out to Kinesis when you deploy the application to AWS. Not only that, but Dapr manages authentication, retries, throttling, and circuit breaking, and has built-in monitoring for all its APIs, insulating developers from having to worry about those mundane yet critical programming practices.

Unlike other distributed programming models, Dapr’s side-car architecture enables code written in any language and the use of any framework to leverage Dapr’s services. Furthermore, applications can use building blocks a la carte, or choose to use them fully. That makes Dapr incrementally adoptable so that you can daprize your existing projects at your own pace. In summary, Dapr is becoming the de facto cloud OS API surface.

In the two years since the first edition of this book was published, the book has helped thousands of .NET developers to jump start their use of Dapr. Since then, Dapr’s capabilities have grown, and so has the number of building blocks. While nothing prevents you from using Dapr APIs directly via HTTP or gRPC, the .NET SDK has kept pace to make idiomatically native .NET interfaces.

Whether you’re new to Dapr, or a Dapr expert and owner of the first edition of this book, this update is for you. There’s no faster way for you to learn not just Dapr, but the tips and tricks that will enable you to focus on your .NET application’s business logic and let Dapr, your cloud-native butler, take care of the rest.

Mark Russinovich Azure CTO and Technical Fellow Microsoft

Contributors

About the author

Davide Bedin is a cloud-native architecture enthusiast, with strong and relevant experience with cloud platforms. As the CTO of an ISV, Davide led its transformation process with the objective of creating new solutions based on the Microsoft Azure cloud. Davide particularly focused on the evolution of distributed computing to service-oriented architectures and, ultimately, microservices, spending most of his developer career creating web services. As a senior cloud solution architect at Microsoft, Davide is responsible for the guidance and support of enterprise customers in embracing the cloud paradigm, a key enabler of their digital transformation; lately, he has also been playing with Dapr.

I thank Francesco Lana, Andrea Tosato, and Marco Zamana for their advice in creating the second edition of this book.

Also, I have been blessed with the wisdom of many great teachers during my career: there are too many to list them all here – you all know who you are.

About the reviewers

Andrea Tosato is a full-stack software engineer and architect on .NET applications. Andrea successfully develops .NET applications in various industries, sometimes facing complex technological challenges. He deals with desktop, web, and mobile development but with the arrival of the Azure cloud, it became his passion. In 2017, he co-founded Cloudgen Verona, a .NET community based in Verona, Italy, with his friend Marco Zamana. In 2019, he was named Microsoft MVP for the first time in the Azure category. Andrea graduated from the University of Pavia with a degree in computer engineering in 2008 and successfully completed his master’s degree, also in computer engineering, from Modena in 2011. Andrea was born in 1986 in Verona, Italy, where he currently works as a remote worker. You can find Andrea on Twitter.

Marco Zamana lives in Verona in the magnificent hills of Valpolicella. He has a background as a software developer and solution architect. He was Microsoft’s Most Valuable Professional for 3 years in the artificial intelligence category.

He currently works as a cloud solution architect engineering at Microsoft. He is the co-founder of Cloudgen Verona, a community that wants to discuss topics related to the cloud and, above all, Azure.

Table of Contents

Preface

Part 1: Introduction to Dapr

1

Introducing Dapr

Technical requirements

Understanding Dapr

What Dapr is not

Exploring Dapr

Setting up Dapr

Docker

Intalling the Dapr CLI

Installing .NET

Installing VS Code

Installing Windows Terminal

Installing Dapr in self-hosted mode

Installing Dapr on Kubernetes

Updating Dapr version

Building our first Dapr sample

Summary

Questions

Further reading

2

Debugging Dapr Solutions

Technical requirements

Configuring VS Code debug for Dapr

Attaching the debugger

Examining the debug configuration

Debugging a Dapr multi-project solution

Creating .NET solutions

Launching the configuration

Tasks

Launching debug sessions individually

Launching compound debug sessions

Using Tye with Dapr

Installing Tye

Using Tye

Summary

Questions

Further reading

3

Microservices Architecture with Dapr

Introducing our sample solution

Discovering microservices

Service

Autonomy

Automated deployment

Bounded context

Loose coupling

Event-driven architecture

Observability

Sustainability

Adopting microservices patterns

Building an e-commerce architecture

Bounded contexts

An example – sales microservices

Building microservices with Dapr

Loosely coupled microservices

Autonomous microservices

Observable microservices

Scalable microservices

Event-driven microservices

Stateless microservices

Summary

Questions

Further reading

Part 2: Building Microservices with Dapr

4

Service-to-Service Invocation

Technical requirements

Invoking services with Dapr

Introducing service-to-service invocation

Name resolution

Resiliency

Service invocation with the .NET SDK

Creating a project for the Order service

Configuring Dapr in ASP.NET

Implementing Dapr with an ASP.NET controller

Creating a project for the Reservation service

Preparing the debugging configuration

Implementing Dapr with an ASP.NET Minimal API

Recap

Comparing HTTP and gRPC for Dapr

gRPC in ASP.NET

Creating a gRPC microservice

Winning latency with gRPC

Summary

Questions

Further reading

5

Introducing State Management

Technical requirements

Managing state in Dapr

State, stateless, and stateful

State stores in Dapr

Transactions

Concurrency

Consistency

Interaction with state stores

Resiliency

Stateful services in an e-commerce ordering system

Stateful reservation-service

Handling the Dapr state in ASP.NET

Using Azure Cosmos DB as a state store

Setting up Azure Cosmos DB

Configuring the state store

Testing the state store

Partitioning with Cosmos DB

Wrapping up

Summary

6

Publish and Subscribe

Technical requirements

Using the pub/sub pattern in Dapr

Using Azure Service Bus (ASB) in Dapr

Subscribing to a topic

Configuring a pub/sub component

Publishing to a topic

Inspecting the messages

Implementing a saga pattern

Publishing messages to Dapr

Subscribing to a Dapr topic

Testing the saga pattern

Summary

7

Resource Bindings

Technical requirements

Learning how to use Dapr bindings

Configuring a cron input binding

Testing the cron binding

Using Twilio output bindings in Dapr

Signing up for a Twilio trial

Configuring a Twilio output binding

Signaling via the output binding

Verifying the notification

Ingesting data with the Azure Event Hubs input binding

Creating an Azure Event Hubs binding

Configuring the input binding

Implementing an Azure Event Hubs input binding

Producing events

Summary

8

Using Actors

Technical requirements

Using actors in Dapr

Introduction to the virtual actor pattern

Configuring a new state store

Verifying the configuration

Actor concurrency, consistency, and lifetime

Placement service

Concurrency and consistency

Resiliency

Lifetime

Implementing actors in an e-commerce reservation system

Preparing the Actor’s projects

Implementing the actor’s model

Accessing actors from other Dapr applications

Inspecting the actor’s state

Summary

Part 3: Deploying and Scaling Dapr Solutions

9

Deploying to Kubernetes

Technical requirements

Setting up Kubernetes

Creating an Azure resource group

Creating an AKS cluster

Connecting to the AKS cluster

Setting up Dapr on Kubernetes

Deploying a Dapr application to Kubernetes

Building Docker images

Pushing Docker images

Managing secrets in Kubernetes

Deploying applications

Exposing Dapr applications to external clients

Summary

10

Exposing Dapr Applications

Technical requirements

Daprizing ingress controllers

Setting up API management on Kubernetes

Configuring Dapr policies with API management

Summary

11

Tracing Dapr Applications

Technical requirements

Observing applications in Dapr

Tracing with Zipkin

Setting up Zipkin

Configuring tracing with Zipkin

Enabling tracing in Dapr

Investigating with Zipkin

Analyzing metrics with Prometheus and Grafana

Installing Prometheus

Installing Grafana

Importing dashboards

Summary

12

Load Testing and Scaling Dapr

Technical requirements

Bash

Python

Locust

Kubernetes configuration

Scaling Dapr on Kubernetes

Replicas

Autoscale

Resource requests and limits

Load testing with Locust

Load testing Dapr

Preparing the data via port-forwarding

Testing Locust locally

Locust on Azure Container Instances

Observing the Horizontal Pod Autoscaler

Autoscaling with KEDA

Summary

13

Leveraging Serverless Containers with Dapr

Technical requirements

Learning about the Azure Container Apps architecture

Understanding the importance of Azure Container Apps

Setting up Azure Container Apps

Deploying Dapr with Azure Container Apps

Configuring Dapr components in Azure Container Apps

Exposing Azure container apps to external clients

Observing Azure container apps

Autoscaling Azure Container Apps with KEDA

Learning about KEDA autoscalers

Applying KEDA to Azure container apps

Testing KEDA with container apps

Summary

Assessments

Index

Other Books You May Enjoy

Preface

Practical microservices with Distributed Application Runtime (Dapr) and .NET helps you discover the powerful capabilities of Dapr by implementing a sample application with microservice architecture, using one of Dapr’s many building blocks in each chapter of this book.

Over the last decade, there has been a huge shift from heavily coded monolithic applications to finer, self-contained microservices. Dapr helps developers build cloud-native applications by providing the building blocks as an easy-to-use API. It offers platform-agnostic features for running your applications on the public cloud, on-premises, and even on edge devices.

This book aims to familiarize you with microservice architecture while managing application complexities and getting into the nitty-gritty of Dapr in no time. You will also see how it combines the simplicity of its implementation with its openness to multiple languages and platforms. We will explore how Dapr’s runtime, services, building blocks, and SDKs will help you simplify the creation of resilient and portable microservices.

Dapr provides an event-driven runtime that supports the essential features you need to build microservices, such as service invocation, state management, and publish and subscribe messaging. You’ll explore all of these in addition to various other advanced features with this practical guide to learning about Dapr.

This book guides you in creating a sample application based on Dapr, which you’ll then deploy to Kubernetes, and the multiple ways of exposing your application to clients that you can leverage, including integrating API Management with Dapr. In this operating environment, you’ll learn how to monitor Dapr applications using Zipkin, Prometheus, and Grafana. After learning how to perform load-testing on Dapr applications in Kubernetes, we will explore how to leverage Dapr with a serverless container service.

By the end of this book, you’ll be able to write microservices easily using your choice of language or framework by implementing the industry best practices to solve any problems related to distributed systems.

Who this book is for

This book is for developers looking to explore microservices architectures and implement them in Dapr applications using .NET examples. Whether you are new to microservices or have knowledge of this architectural approach and want to get hands-on experience of using Dapr, you’ll find this book useful. Familiarity with .NET will help you to understand the C# samples and code snippets used in the book.

What this book covers

Chapter 1, Introducing Dapr, will introduce you to the basics of Dapr, briefly exposing the features that make Dapr interesting for new cloud-native applications, as well as for inserting microservices into existing applications.

Chapter 2, Debugging Dapr Solutions, will focus on how to set up your Dapr development environment in VS Code to locally debug simple Dapr solutions, as well as more complex ones.

Chapter 3, Microservices Architecture with Dapr, will discuss the relevance of microservices architectures and starts to explore how Dapr as a runtime can make it easier to adopt this style. 

Chapter 4, Service-to-Service Invocation, will instruct you on how services can discover and invoke each other via the Dapr infrastructure. With examples, you will understand how to implement services and invoke them from other Dapr-aware components and Dapr-unaware or external clients.

Chapter 5, Introducing State Management, will illustrate how a Dapr solution can manage states with different store types. Managing states for services and actors is a centerpiece of Dapr.

Chapter 6, Publish and Subscribe, will teach you about publish and subscribe, which is the messaging pattern used by Dapr to enable decoupled interactions between components. Input bindings enable you to trigger your microservice using an incoming Twilio SMS or an Azure Service Bus message.

Chapter 7, Resource Bindings, will detail how input bindings in Dapr enable you to design event-driven microservices and invoke external resources via a pluggable configuration.

Chapter 8, Using Actors, will help you learn about the powerful virtual actor model provided by Dapr, how to leverage it in a microservices-style architecture, and the pros and cons of different approaches.

Chapter 9, Deployment to Kubernetes, will help distinguish the basic differences between local Standalone mode and Kubernetes mode in terms of their operations. Specifically using Azure Kubernetes Service, we will deploy a Dapr sample application composed of several microservices to Kubernetes.

Chapter 10, Exposing Dapr Applications, will explore how we can expose our Dapr applications to our end users. Specifically using Azure Kubernetes Service, we will expose our Dapr sample application on Kubernetes via NGINX and Azure API Management.

Chapter 11, Tracing Dapr Applications, will outline the observability options in Dapr by exploring how traces, logs, and metrics are emitted and can be collected in Dapr using Zipkin, Prometheus, and Grafana.

Chapter 12, Load-Testing and Scaling Dapr, will elaborate on how the scaling of Dapr services and actors works in Kubernetes, and by leveraging Locust, the reader will also learn how to load-test a Dapr solution by simulating user behaviors via the Locust testing tool.

Chapter 13, Leveraging Serverless Containers with Dapr, will guide you on how to benefit from Kubernetes without its complexities by adopting serverless containers with Azure. We will understand how to deploy a Dapr application to Azure Container Apps.

To get the most out of this book

While the samples in the book have been written on Windows 10, the technology stack used is multiplatform: VS Code, .NET 6, Dapr, Kubernetes, and Locust all offer tools and libraries for multiple platforms.

On Windows 10, it is recommended to have WSL 2 installed and enable the WSL 2 engine in Docker.

For detailed instructions on how to set up your environment, please see the Setting up Dapr section in Chapter 1, Introducing Dapr.

The samples and scripts in this book have been tested with Dapr version 1.8 and .NET 6.

Software/hardware covered in the book

Operating system requirements

Docker Engine – latest version

Windows, any version supporting .NET 6

.NET 6

Windows, any version supporting .NET 6

Dapr 1.8 or later

Windows, any version supporting .NET 6

VS Code – latest version

Windows, any version supporting .NET 6

Azure CLI – latest version

Windows, any version supporting .NET 6

Python 3.8 or later

Windows, any version supporting .NET 6

Locust 2.10 or later

Windows, any version supporting .NET 6

Access to an Azure subscription is required, as the samples leverage many Azure services. Each chapter will give you instructions and direct you to the documentation for further information.

If you are using the digital version of this book, we advise you to type the code yourself or access the code from the book’s GitHub repository (a link is available in the next section). Doing so will help you avoid any potential errors related to the copying and pasting of code.

After reading this book, continue your learning by looking through the Dapr documentation at https://docs.dapr.io/ and follow the community meetings at https://github.com/dapr/community#community-meetings; these are a great opportunity to learn, ask questions, and share your experience with Dapr.

Download the example code files

You can download the example code files for this book from GitHub at https://github.com/PacktPublishing/Practical-Microservices-with-Dapr-and-.NET-Second-Edition. If there’s an update to the code, it will be updated in the GitHub repository.

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 and diagrams used in this book. Please refer to this graphic bundle for better readability of images. You can download it here: https://packt.link/eSCK1

Conventions used

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

Code in text: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: “The –-debug * option of the Tye command waits for VS Code debug sessions to be attached to each service.”

A block of code is set as follows:

"compounds":    [      {        "name": "webApi + webApi2 w/Dapr",        "configurations": [".NET Core Launch w/Dapr          (webapi)", ".NET Core Launch w/Dapr (webapi2)"]      }    ]

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

     {         "name": ".NET Core Launch w/Dapr (webapi2)",         "type": "coreclr",         "request": "launch",         "preLaunchTask": "daprd-debug-webapi2",

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

PS C:\> curl http://localhost:60151/v1.0/invoke/hello-world/method/hello

Hello, World

Bold: Indicates a new term, an important word, or words that you see onscreen. For instance, words in menus or dialog boxes appear in bold. Here is an example: “Once we activate debugging in VS Code by selecting the .NET Core Launch (web) with Dapr configuration, this is what happens.”

Tips or important notes

Appear like this.

Get in touch

Feedback from our readers is always welcome.

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

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 www.packtpub.com/support/errata and fill in the form.

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 authors.packtpub.com.

Share Your Thoughts

Once you’ve read Practical Microservices with Dapr and .NET - 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.

Download a free PDF copy of this book

Thanks for purchasing this book!

Do you like to read on the go but are unable to carry your print books everywhere?

Is your eBook purchase not compatible with the device of your choice?

Don’t worry, now with every Packt book you get a DRM-free PDF version of that book at no cost.

Read anywhere, any place, on any device. Search, copy, and paste code from your favorite technical books directly into your application.

The perks don’t stop there, you can get exclusive access to discounts, newsletters, and great free content in your inbox daily

Follow these simple steps to get the benefits:

Scan the QR code or visit the link below

https://packt.link/free-ebook/978-1-80324-812-7

Submit your proof of purchaseThat’s it! We’ll send your free PDF and other benefits to your email directly

Part 1: Introduction to Dapr

This first part of the book will give you a starting point on Dapr with an overview of what it is and its main features and components. By understanding how to debug with Dapr, you will gain confidence in exploring the building blocks.

This part contains the following chapters:

Chapter 1, Introducing DaprChapter 2, Debugging Dapr SolutionsChapter 3, Microservices Architecture with Dapr

1

Introducing Dapr

Welcome to this second edition of Practical Microservices with Dapr and .NET! Distributed Application Runtime (Dapr) evolved greatly after the version one release and the innovations in .NET 6 prompted a refreshed and enriched edition of the book.

This chapter will introduce you to the Dapr project to teach you the core concepts of its architecture and prepare you to develop with Dapr.

Dapr accelerates the development of new cloud-native applications and simplifies the adoption of a microservice architecture.

In this chapter, we are going to cover the following main topics:

Understanding DaprExploring Dapr Setting up DaprBuilding our first Dapr sample

Learning about these topics is important to establish a solid foundation for our future endeavors with Dapr and microservice architectures. These basic concepts will guide our learning throughout the rest of this book.

Our first steps into the project will start with exploring Dapr and understanding how it works.

Technical requirements

The code for this sample can be found on GitHub at https://github.com/PacktPublishing/Practical-Microservices-with-Dapr-and-.NET-Second-Edition/tree/main/chapter01.

In this chapter, the working area for scripts and code is expected to be <repository path>\chapter01\. In our local environment, it is C:\Repos\practical-dapr\chapter01.

Please refer to the Setting up Dapr section for a complete guide to the tools needed to develop with Dapr and work with the samples.

Understanding Dapr

Dapr is an event-driven, portable runtime created by Microsoft with an open source approach and it is a Cloud Native Computing Foundation (CNCF) incubated project.

Being event-driven (which is emphasized in the definition of Dapr) plays an important role in microservices; this is because an application can be designed to efficiently react to events from external systems or other parts of the solution and to produce events as well in order to inform other services of new facts or to continue processing elsewhere, or at a later stage.

Dapr is portable as it can run locally on your development machine in self-hosted mode; it can also be deployed to the edge, or it can run on Kubernetes.

The following diagram shows the many building blocks provided by Dapr:

Figure 1.1 – Dapr architecture

Portability does also extend beyond the hosting environment—while Dapr is an initiative that was started by Microsoft, it can also run on Kubernetes on-premises or in the cloud with Microsoft Azure, Amazon Web Services (AWS), Google Cloud Platform (GCP), or any other cloud vendor.

Dapr has been built on the experience gained by Microsoft in developing hyperscale cloud-native applications. It has been inspired by the design of Orleans and Service Fabric, which in turn enables many Microsoft Azure cloud services to operate resiliently and at a large scale.

A brief history of Dapr

Dapr was first released in October 2019, and you can find more information at https://cloudblogs.microsoft.com/opensource/2019/10/16/announcing-dapr-open-source-project-build-microservice-applications/.

Dapr adopted an open governance model early on in the initial development phase in September 2020; see the description at https://blog.dapr.io/posts/2020/09/30/transitioning-the-dapr-project-to-open-governance/.

Dapr reached the production-ready v1.0 release in February 2021; see https://blog.dapr.io/posts/2021/02/17/announcing-dapr-v1.0/ for more details. In November 2021, Dapr joined CNCF as an incubated project; see the announcement at https://blog.dapr.io/posts/2021/11/03/dapr-joins-cncf-as-an-incubating-project/.

Dapr offers developers an approach to design the tools to build and the runtime to operate applications, based on a microservice architecture style.

Microservices offer a vast array of benefits balanced by increased complexities in team and product management, usually with a significant burden on the developer and the team in order to get started.

What if you could leverage a runtime such as Dapr to help you get through the common patterns you will likely need to adopt, and thus ease your operations?

The following figure shows the two Dapr hosting modes:

Figure 1.2 – Dapr sidecar

As depicted in Figure 1.2, the Dapr runtime operates in sidecar processes, lifting most of the complexity from the application to a separate environment, greatly simplifying development and operations as well. These sidecar processes are run locally in your development environment or as containers in a Pod on Kubernetes.

From an application perspective, Dapr is an Application Programming Interface (API) that can be directly reached via HyperText Transfer Protocol (HTTP), Remote Procedure Call (gRPC) calls, or, even more simply, via any of the Software Development Kits (SDKs) available for .NET, Java, Go, Python, PHP, JavaScript, C++, and Rust languages.

As we will experience later, it is not necessary to adopt the Dapr SDK in your application; a request to a Dapr service can be as simple as an HTTP call to an endpoint, such as http://localhost:3500/v1.0/invoke/<app-id>/method/<methodname>. Nevertheless, using the SDK does provide many benefits if you are writing a Dapr service adopting the server extensions, interacting with Dapr via the client SDK, or leveraging the Dapr actor model with the Actor SDK.

You can learn more about SDKs and the supported languages in the Dapr docs at https://docs.dapr.io/developing-applications/sdks/.

Now that we have learned about the high-level architecture of Dapr, it is time to also clarify what Dapr is not.

What Dapr is not

While we hope the overview of Dapr has informed and intrigued you enough to spend time on this book, when we have the chance to talk about Dapr, we often find ourselves in need of clarifying what Dapr is not. This makes it easier to eliminate any misconceptions we may have about what Dapr does, as follows:

Dapr does not force the developer to embrace a programming model with strict rules and constraints. On the contrary, while the application developer is freed, by Dapr, of the many complexities of a microservice architecture, the developer is not mandated on how to write the application. As an example, the management of the connection to the database where the state is stored is a responsibility of Dapr and, as we will see in the following chapters, it is transparent to the microservice application code.Dapr is not a service mesh. While many similarities can be found in the general objectives of Dapr and service meshes, Dapr does provide these benefits at the application level, while a service mesh operates on the infrastructure. For instance, it is the developer’s responsibility to decide how to handle errors Dapr might return if there is a conflict or an intermittent issue; whether it is adopting a retry policy as provided by the Dapr resiliency configurations, raising an error back to the client, or compensating the operation, these are explicit choices only the developer can make.

Dapr is designed to be integrated with service meshes such as Istio, which is out of the scope of this book.

Dapr is not a Microsoft cloud service. It does help the developer build microservice applications in the cloud, and it surely provides many integrations with Azure cloud services, but it also has as many components for AWS, GCP, and other services. At the same time, Azure does offer rich support to Dapr in Azure Kubernetes Service (AKS) with the native extension, in Azure API Management with Dapr policies, and in Azure Container Apps with Dapr native integration.Dapr is not a .NET only technology. Dapr itself has been written in the Go language and any language can leverage it. SDKs for many languages are available but you can also choose to interact directly with the Dapr API without any additional library.

Important note

While this book is heavily skewed toward .NET, Dapr does provide the same benefits to Python developers (just as an example) as it provides SDKs for Dapr and Dapr Actor, with Kubernetes as the deployment target—Dapr welcomes all developers in a vendor-neutral and open approach.

We hope this perspective on the Dapr objectives and role will help you in properly adopting this technology. The next section will be dedicated to understanding the architecture of Dapr.

Exploring Dapr

Dapr has been designed from the ground up as a set of pluggable building blocks—developers can create an application counting on the support of many facilities, while operators can adapt applications to the hosting environment by simply intervening in the configuration.

The following is a complete list of the tools and components of Dapr:

The Dapr command-line interface (CLI): A cross-platform command-line tool to configure, manage, and monitor the Dapr environment. It is also the tool used to locally debug Dapr applications.Dapr Helm charts: It is worth mentioning that Helm charts are provided for a richer experience in installing and updating Dapr in a Kubernetes environment. The Dapr API: The API that defines how an application can interact with the Dapr runtime in order to leverage its building blocks.The Dapr runtime: This is the core of Dapr that implements the API. If you are curious, you can take a look at how it is developed in Go at Dapr’s repository at https://github.com/dapr/dapr.The Dapr host: On your development machine, the host runs as a standalone process; in Kubernetes, it is a sidecar container in your application’s pod.The Dapr operator: Specific to Kubernetes mode, the operator manages bindings and configurations.The Dapr sidecar injector: Once instructed via configuration in Kubernetes mode, this takes care of injecting the Dapr sidecar into your application pod.The Dapr placement service: This service has the objective of distributing (or placing) Actor instances across the Dapr pods.Dapr Sentry: A built-in Certificate Authority (CA) to issue and manage certificates used by Dapr to provide transparent mutual Transport Layer Security (mTLS).

Dapr provides several building blocks that microservice application developers can adopt selectively, based on their needs, and they are as follows:

Service invocation: Service-to-service invocation enables your code to call other services located in the same hosting environment while taking care of the retry policy.

This building block is presented in more detail in Chapter 4, Service-to-Service Invocation.

State management: This is to efficiently manage the application state as a simple Key-Value Pair (KVP), relieving your stateful or stateless services of the need to support different backends. Dapr provides many state stores, which include Redis, Azure Cosmos DB, Azure SQL Server, and PostgreSQL, which can be plugged in via configuration.

You can learn about this building block in Chapter 5, Introducing State Management.

Publish and subscribe (pub/sub) messaging: The pub/sub pattern enables decoupled communication between microservices by exchanging messages, counting on the presence of a service bus, which can route messages between producers and consumers.

A discussion of this building block is presented in Chapter 6, Publish and Subscribe.

Resource bindings: This is where the event-driven nature of Dapr shines. With bindings, your application can be triggered by a Short Message Service (SMS) message sent via Twilio (just one of the popular services in the area of communication API).

This building block is presented in more detail in Chapter 7, Resource Bindings.

Actors: The actor pattern aims to simplify highly concurrent scenarios by splitting the overall request load between a large number of computation units (the actors), which take care of the job in their smaller, but independent, scope by processing requests to a single actor one at a time. Dapr provides great benefits in this space.

You can learn about this building block in Chapter 8,Using Actors.

Observability: Dapr enables the developer and operator to observe the behavior of the system services and applications without having to instrument them.

This building block is presented in more detail in Chapter 11, Tracing Dapr Applications.

Secrets: It is a healthy practice to keep secrets segregated from the code. Dapr enables you to store secrets and to reference these from other components, in Kubernetes or Azure Key Vault, among many options.Configuration: Introduced in Dapr version 1.8 in Alpha state, this building block addresses the common need to retrieve the configuration data needed by an application.Distributed lock: Introduced with Dapr version 1.8 in Alpha state, it provides a powerful lease-based mechanism to manage mutually exclusive access to a named lock. The lock can be used by the application to assure exclusive access to a resource by many concurrent instances.

After learning about Dapr architecture and components, and before we can start using them, we need to set up Dapr in our development environment, which will be the topic of the next section.

Setting up Dapr

Dapr is a runtime for every platform and every language. The focus of this book is on C# in .NET, used with Visual Studio Code (VS Code). The code snippets in the book can be appreciated by developers from any background, but nevertheless, you will get the most out of it from a .NET perspective.

The development environment we use is Windows, as you will be able to tell from the screenshots we use in the book. While the CLI, configuration, and files will be the same, if you need more details on how to perform a particular action on Linux or a macOS development machine, we encourage you to check the Dapr documentation at https://docs.dapr.io/.

Dapr roadmap

The Dapr runtime reached the v1.0 production-ready release in February 2021, as announced in the Dapr blog at https://blog.dapr.io/posts/2021/02/17/announcing-dapr-v1.0/, and five new minor versions have been released during 2021. You can learn more about the Dapr roadmap at https://docs.dapr.io/contributing/roadmap/.

The samples and scripts in this book have been updated and tested with v1.8 of Dapr.

In this book, we will also leverage several services on the Azure cloud platform (https://azure.microsoft.com/en-us/explore/), whether as a platform to execute Dapr applications, for exchanging messages via Azure, or for storing data.

Access to an Azure subscription is required. Each chapter will give you instructions and direct you to documentation for further information.

Next, we will accomplish the following steps:

Configuring DockerInstalling the Dapr CLIInstalling .NETInstalling VS CodeInstalling Windows TerminalInstalling Dapr in self-hosted mode Installing Dapr on Kubernetes

Let’s start with Docker.

Docker

Dapr requires Docker to be present locally in your development environment; therefore, make sure you have it installed. If your development machine is Windows, Docker must be running in Linux container mode.

You can find detailed instructions for running Docker at https://docs.docker.com/install/.

Intalling the Dapr CLI

We will immediately start working with Dapr; therefore, you need to install all the necessary tools. The Dapr runtime and its tools can be found at https://github.com/dapr/cli.

On Windows, execute the following command to install the CLI in the c:/dapr directory and add it to the user PATH environment variable so that the tools can be easily found from the command line:

powershell -Command "iwr -useb https://raw.githubusercontent.com/dapr/cli/master/install/install.ps1 | iex"

For more details on the Dapr CLI, please refer to https://docs.dapr.io/getting-started/install-dapr-cli/.

We still need to initialize Dapr on the development machine, which we will do in the Installing Dapr in self-hosted mode section of this chapter.

Installing .NET

To install .NET 6, please refer to https://dotnet.microsoft.com/download for the link to the latest binaries.

.NET 6 is a Long-Term Support (LTS) version of .NET, which gets free support and patches for 3 years. Refer to https://dotnet.microsoft.com/en-us/platform/support/policy for more details on the .NET support policy.

On a development machine, it makes sense to install the full SDK, which includes the runtime. Once the install is complete, open a new command prompt and run the dotnet --info command. You should see the following output:

PS C:\Repos\dapr-samples\chapter01> dotnet --info .NET SDK (reflecting any global.json): Version:   6.0.101 Commit:    ef49f6213a Runtime Environment: OS Name:     Windows OS Version:  10.0.22000 OS Platform: Windows RID:         win10-x64 Base Path:   C:\Program Files\dotnet\sdk\6.0.101\ Host (useful for support):   Version: 6.0.1   Commit:  3a25a7f1cc …

This proves that .NET has been recognized and the framework is working fine.

Installing VS Code

VS Code is a great multiplatform source code editor by Microsoft. You can install it for free by following the instructions at https://code.visualstudio.com/docs/setup/windows.

The Dapr extension

Dapr has an extension for VS Code that helps with navigating the Dapr local environment and eases the debugging configuration—we highly recommend it. Please follow the instructions at https://docs.dapr.io/developing-applications/ides/vscode/.

Installing Windows Terminal

We really love the new Windows Terminal (https://aka.ms/terminal) for its ease of use and configurability. In the following chapters, we will often have to run multiple commands and tools in parallel. Therefore, the tabs feature of Windows Terminal is just one of the reasons why we suggest you adopt it too.

Installing Dapr in self-hosted mode

Dapr can be initialized in two modes: self-hosted (or standalone) and Kubernetes.