Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make an Http request through a Lambda Func

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

like image 845
Teragon Avatar asked Sep 01 '25 05:09

Teragon


1 Answers

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;
}
like image 166
Piotr Avatar answered Sep 02 '25 17:09

Piotr