I'm trying make httpclient requests through a helper function that will manage a circuitbreaker polly policy.
I'm trying to call it like so
var response = clientFactory.MakeRequest(() => client.GetAsync("/"));
Inside of the client factory I have my circuit breaker policy defined and I'm trying to execute the lambda above using that policy like so
public async Task<HttpResponseMessage> MakeRequest(Func<HttpResponseMessage> request)
{
var response = policy.ExecuteAsync(() => request.Invoke());
return response;
}
I'm fairly new to Lambda's as a whole and passing it as a function gets more confusing. How do I configure the function and the first line of code to execute the client and return the HttpResponseMessage
? I don't think Task<HttpResponseMessage>
or Func<HttpResponseMessage>
is correct
I would suggest, that you read some information on async/await (not lambdas) as this is the key to understanding how to achieve it.
https://learn.microsoft.com/en-us/dotnet/csharp/async
You are using asynchronous programming so must decide, whether you want to have asynchronous method MakeRequest or you want synchronous one. If you want synchronous (but then - no need for using ExecuteAsync. I suppose, that there is Execute() alternative) simple write :
public HttpResponseMessage MakeRequest(Func<HttpResponseMessage> request)
{
var response = policy.Execute(() => request.Invoke());
return response;
}
if you want asynchronous :
public async Task<HttpResponseMessage> MakeRequest(Func<HttpResponseMessage> request)
{
var response = await policy.ExecuteAsync(() => request.Invoke());
return response;
}
public Task MyMethodUsingAsync()
{
var responsePromises = MakeRequest(() => {...});
///do some job wich will be done before response is retrieved (not waiting for it); and if you need it - use await
var responseReceived = await responsePromises;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With