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.
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.
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.
As previously, we inject the interface in our web API controller of our first service, so that it can call the second service.
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.
public void ConfigureServices(IServiceCollection services)
Here is the same result
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.