Sai A Sai A
Updated date May 15, 2023
In this article, we will provide an introduction to building microservices with Dapr and .NET Core. The article covers the basics of getting started with Dapr, creating a service with Dapr, and creating multiple services that communicate with each other using Dapr's service discovery feature.

Introduction:

Microservices are becoming increasingly popular in modern application development due to their ability to create scalable, decoupled, and easily deployable applications. Dapr (Distributed Application Runtime) is an open-source framework that provides developers with a set of building blocks to build microservices-based applications. Dapr makes it easier for developers to build, deploy and manage microservices applications by providing features such as service discovery, state management, pub/sub messaging, and more. In this article, we will explore how to build microservices with Dapr and .NET Core.

Getting Started with Dapr:

To get started with Dapr, you will need to install the Dapr runtime. The easiest way to install the Dapr runtime is to use the Dapr CLI. You can download and install the Dapr CLI from the Dapr website.

Once you have installed the Dapr CLI, you can initialize Dapr in your .NET Core application using the following command:

dapr init

This command will create a Dapr configuration file in your application and install the necessary dependencies.

Building Microservices with Dapr:

To build microservices with Dapr, you will need to create multiple services that communicate with each other using Dapr. Let's start by creating a simple .NET Core application that uses Dapr for service discovery.

Creating a Service with Dapr:

Create a new .NET Core console application and add the Dapr NuGet package to your project.

dotnet new console -n DaprDemo
cd DaprDemo
dotnet add package Dapr

Next, add the following code to your Program.cs file:

using Dapr;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;

namespace DaprDemo
{
    public class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                })
                .UseDapr();
    }
}

In the code above, we are using the Dapr SDK to create a new .NET Core application that uses Dapr. The UseDapr() method registers Dapr with the application and sets up the necessary configuration for Dapr to work.

Next, create a new Startup.cs file and add the following code:

using Dapr.Client;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;

namespace DaprDemo
{
    public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            services.AddDaprClient();
        }

        public void Configure(IApplicationBuilder app)
        {
            app.UseRouting();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
                endpoints.MapGet("/", async context =>
                {
                    var client = context.RequestServices.GetRequiredService<DaprClient>();
                    var result = await client.InvokeMethodAsync<string>("service-a", "api/values");
                    await context.Response.WriteAsync(result);
                });
            });
        }
    }
}

In the code above, we are using the DaprClient to invoke a method on another service called service-a. The service-a is registered with Dapr, and Dapr will automatically discover the endpoint for this service.

Creating Multiple Services with Dapr:

Now that we have created our first microservice with Dapr, let's create another microservice that communicates with the first microservice. Create a new .NET Core console application and add the Dapr NuGet package to your project.

dotnet new console -n DaprDemo2
cd Dapr

Next, add the following code to your Program.cs file:

using Dapr;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;

namespace DaprDemo2
{
    public class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                })
                .UseDapr();
    }
}

In the code above, we are using the Dapr SDK to create a new .NET Core application that uses Dapr. The UseDapr() method registers Dapr with the application and sets up the necessary configuration for Dapr to work.

Next, create a new Startup.cs file and add the following code:

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;

namespace DaprDemo2
{
    public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
        }

        public void Configure(IApplicationBuilder app)
        {
            app.UseRouting();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
                endpoints.MapGet("/", async context =>
                {
                    await context.Response.WriteAsync("Hello from service-b!");
                });
            });
        }
    }
}

In the code above, we have created a new microservice called service-b that returns a simple message.

Now, let's modify our first microservice to invoke a method on service-b. Modify the Startup.cs file in the first microservice as follows:

using Dapr.Client;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;

namespace DaprDemo
{
    public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            services.AddDaprClient();
        }

        public void Configure(IApplicationBuilder app)
        {
            app.UseRouting();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
                endpoints.MapGet("/", async context =>
                {
                    var client = context.RequestServices.GetRequiredService<DaprClient>();
                    var result = await client.InvokeMethodAsync<string>("service-b", "api/values");
                    await context.Response.WriteAsync(result);
                });
            });
        }
    }
}

In the code above, we have modified the method that is invoked when a request is made to the root of the application. We are now invoking a method on service-b and returning the result.

Conclusion:

In this article, we have explored how to build microservices with Dapr and .NET Core. We have created two microservices that communicate with each other using Dapr's service discovery feature. Dapr provides a set of building blocks that make it easier for developers to build, deploy and manage microservices-based applications. With Dapr, developers can focus on writing business logic and let Dapr handle the complexity of managing microservices.

Comments (0)

There are no comments. Be the first to comment!!!