A DotNet Raider

My adventures in the .NET world!
posts - 49, comments - 12, trackbacks - 0

My Links

News

Website View Martino Bordin's profile on LinkedIn

Archives

Post Categories

Dapr - Create a Dapr service

In order to use Dapr with C#, you just have to create a new ASP.NET Core Web API Project and reference the Nuget package Dapr.AspNetCore

Once done, just go in the Program.cs and chain the method AddDapr() after the method AddControllers():

builder.Services.AddControllers().AddDapr();

In addition to that, just call these methods to register the Pub\Sub building block:

app.MapSubscribeHandler();

app.UseCloudEvents();

At this point, you can inject the DaprClient, in your controller or services, to interact with the several APIs of Dapr.

public CustomersController(DaprClient daprClient)
{
  this.daprClient = daprClient;
}


We then can run the application along with Dapr sidecar using the CLI

dapr run --app-id microdelivery.customers.api --app-port 8000 -- dotnet run

But, since we're going to create several microservices, I prefer the docker-compose approach. Here the YAML file for the customer's microservice (microdelivery.customers.api) and its sidercar (microdelivery.customers.api.dapr).


version: '3.4

services:
  # Customers Api & Sidecar
  microdelivery.customers.api:
    container_name: microdelivery.customers.api
    image: ${DOCKER_REGISTRY-}microdeliverycustomersapi
    build:
      context: .
      dockerfile: src/MicroDelivery.Customers.Api/Dockerfile
    depends_on:
      - sqlserver
      - redis
    environment:
      - ASPNETCORE_ENVIRONMENT=Development
    ports:
      - "8000:80"

  microdelivery.customers.api.dapr:
    container_name: microdelivery.customers.api.dapr
    image: "daprio/daprd:latest"
    network_mode: "service:microdelivery.customers.api"
    depends_on:
      - microdelivery.customers.api
    command: ["./daprd",
      "-app-id", "microdelivery-customers-api",
      "-app-port", "80",
      "-resources-path", "/components",
      "-config", "/configuration/configuration.yaml",
      "-log-level", "debug"
      ]
    volumes:
      - "./dapr/components/:/components"
      - "./dapr/configuration/:/configuration"'

The sidecar is a docker image (daprio/daprd) attached to the network of the customer's microservices where we execute the daprd command, passing some parameters like the app id that identifies our app, the app port, what is the components\config path to customize our microservices behavior and the log level.

We can then just run the application with Visual Studio that will create the two containers and we're ready to debug it!

In the next article, we'll see the first building block: State management

Print | posted on lunedì 3 luglio 2023 09:19 | Filed Under [ Dapr Microservices ]

Comments have been closed on this topic.

Powered by:
Powered By Subtext Powered By ASP.NET