'Creating an API in shared library in .NET Core
In our microservices architecture there are several APIs that are part of shared library included with each service. We want these APIs (ex. /cache/delete) to appear in all services. However, what we cannot figure out is how to dynamically assign the URL route. So what we need is the URL route base (specific to the service) would be prefixed to the resource/action. For example:
https://example.com/api/service1/cache/delete
https://example.com/api/service2/cache/delete
In C# v10 interpolated constant strings were introduced, that would allow something like [Route($"{prefix}/cache/delete)]. But we will not be on this version for a while.
I was wondering if there is another possible implementation for this.
Solution 1:[1]
It sounds like you have each service do its own route prefix. I'm not typically a fan of that as I just have other things do that, like the API gateway or use some sort of service discovery tool (Consul, service discovery in Kubernetes, etc.).
If you did this, you'd be able to just map to /cache and it would make life easy on both ends (the service and the library).
If you want to keep the same pattern you're currently doing, you can tap into IEndpointRouteBuilder. Each service can then use the default you set (/cache), or define their own endpoint. That's where the service can insert their own prefix and you take the responsibility off of the library for making sure it has the right endpoint.
Trying to do a catch-all generic library that deals with something like that routing, which is specific to each service is asking for trouble. You would be forcing yourself into the same routing pattern for every service you ever make that uses caching even though you may want something else. Allow the route to be flexible and managed by the service rather than coupling the two together like that.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Zach Sexton |
