Type safety when using requestUri of HttpClient.GetAsync(String) in Micro Services

155 views Asked by At

In a micro-service architecture in .NET, there are many WebAPI services. They interact each other with Uri which are primarily strings.

HttpClient client = new HttpClient()
client.BaseAddress = new Uri("http://localhost:9000/");

HttpResponseMessage response = await client.GetAsync("api/products/1");
HttpResponseMessage response = await client.GetAsync("api/products");

The magic strings like api/products/1 causes code maintainability problem - the magic strings are spread in the code. The consumer or the client application can break if there service changes in the apicontroller or the action. There is no proxy like WCF provides where the client can use type safe service calls.

How can I bring the type safety to webapi service calls?

1

There are 1 answers

5
ManOVision On

These micro services should not be coupled together and communicating directly with each other. One of the key points of micro services is to decouple so the services are not dependent on each other. This way one micro service can be taken down or updated and the rest of the micro services are not affected. If you use an API Gateway, this gateway is the only thing that would need to change if services change. If direct service-to-service communication is needed, I would use a messaging or queue service to facilitate this. Now each service could subscribe to what it needs from the other services without knowing what it's endpoints (or interfaces are). Only the gateway knows about the micro service's interfaces and can update if the interfaces are changed. Now the API Gateway is the only interface external clients need to know about. These interfaces can now have a versioning strategy and these interfaces are the only ones that are "public". No micro service interfaces should be public.