I am trying to find a way to use a HttpClient
using IHttpClientFactory.CreateClient([name])
where [name] is an HttpClient
that was configured using Polly
in the Startup class using PolicyRegistry
.
I want that policy to apply for each of the urls that i make calls using that client.
So if I create a client called "myclient" and throughout my application I will make calls to N different urls , using that named client, I want to have the policy applied for each url individually , not as a whole.
Startup
PolicyRegistry registry = new PolicyRegistry();
AsyncPolicyWrap type1Policy = //somePolicy;
registry.Add("type1",type1Policy);
services.AddHttpClient("someClient").AddPolicyHandlerFromRegistry("type1");
Some Consumer Service
public class SomeService
{
private IHttpClientFactory factory;
public SomeService(IHttpClientFactory factory)
{
this.factory=factory;
}
public void SomeCall(string url)
{
var client=factory.GetClient("someClient");
client.SendAsync(...);
}
}
In the above case I want the policy set up in the startup class to be taken individually for each of the urls that I am calling.
Is that possible ?
In order to achieve that you need to register your HttpClient and your PolicyRegistry separately:
Then you can ask the DI to provide that registry for you:
Finally inside your
SomeCall
you can retrieve the policy:UPDATE #1: Create new policy per url
In functional programming there is a well-known technique, called Memoization. It basically memorizes / caches the output of a method based on the received parameters. In other words if the method receives the same input then it emits the result from a cache rather than re-executing it.
This technique works fine for pure functions. They return the same value if they receive the exact same input in a side effect free way.
So, if we can have a solution which
Here is a simple implementation, but you can find a lots of variations like 1, 2, 3, etc.
ConcurrenctDictionary
to ASP.NET's MemoryCacheHere is a sample for usage:
You can register the memoizer as a singleton and you are ready to use it. :D
I hope it helps you to achieve the desired behaviour.