In the last post, we have seen how to call a service from another service using the Dapr .NET SDK. In this one, we will have a look at a possible way to simplify the development of the client code using Refit, the automatic type-safe REST library for .NET Core, Xamarin, and .NET.

Introduction

Refit is a library heavily inspired by Square’s Retrofit library, and it turns your REST API into a live interface! It generates for you an implementation of the interface that uses HttpClient to make its calls.
Coupled to the Dapr .NET SDK it is a great candidate to reduce the amount of code you need to write to call your Dapr services. And we all know, less code means fewer bugs.

Proxy service

The only difference from the previous blog post source code for the IWeatherForecastClient interface is that we decorate the interface with a Get attribute coming from Refit and specifying the method on the service which is called, here weatherforecast.

IWeatherForecastClient.cs
1
2
3
4
5
6
7
8
9
10
11
12
using System.Collections.Generic;
using System.Threading.Tasks;
using Refit;

namespace WeatherForecastProxyService
{
public interface IWeatherForecastClient
{
[Get("/weatherforecast")]
Task<IEnumerable<WeatherForecast>> GetWeatherForecast(int count);
}
}

As previously, we inject the interface in our web API controller of our first service, so that it can call the second service.

WeatherForecastProxyController.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
[ApiController]
[Route("[controller]")]
public class WeatherForecastProxyController : ControllerBase
{
private readonly IWeatherForecastClient _weatherForecastClient;

public WeatherForecastProxyController(IWeatherForecastClient weatherForecastClient)
{
_weatherForecastClient = weatherForecastClient;
}

[HttpGet]
public async Task<IEnumerable<WeatherForecast>> Get(int count)
{
return await _weatherForecastClient.GetWeatherForecast(count);
}
}

Finally, we need to configure the ASP.NET IOC container, so that it can inject the client based on IWeatherForecastClient created by Refit into the controller. Again, we leverage the Dapr .NET SDK to create the HttpClient using the Dapr appid backend which was used to start our backend service through Dapr. This is the way that the HttpClient knows how to call our backend service and decoupling it from its real address, letting Dapr handle the resolution of its location.

Startup.cs
1
2
3
4
5
6
7
8
public void ConfigureServices(IServiceCollection services)
{
...

services.AddSingleton(
_ => RestService.For<IWeatherForecastClient>(
DaprClient.CreateInvokeHttpClient("backend")));
}

Here is the same result

Calling the proxy using Refit

Conclusion

In this post, we used Refit to simplify the development of the client code needed to call a Dapr service.

You can get access to the code of this blog post on GitHub in the ServiceToService Refit folder.