I'm creating an instance of HttpRequestMessage and return it to be used through the HTTP client.
HttpClient Client { get; init }
HttpRequestMessage GenerateRequest() { ... }
Then, I'm using Polly to execute the call under a policy with a couple of iterations and exponential delay in between.
using HttpResponseMessage response = await RetryPolicy
.ExecuteAsync(() => Client.SendAsync(GenerateReqest()));
Since HttpRequestMessage implements IDisposable, I've been recommended to ensure invocation of Dispose() as the object goes out of scope, like this:
using HttpResponseMessage response = await RetryPolicy
.ExecuteAsync(() =>
{
using HttpRequestMessage request = GenerateRequest();
Client.SendAsync(request);
});
Is there a simpler syntax to achieve that? I could call the disposer explicitly but that doesn't change the fact that I still would have to wrap it in a body instead of going simple lambda expression, which I'd prefer.
I went through the HttpRequestMessage class and it's Dispose() as well as the underlying HttpContext and so on. As far I can see, there's no actual registration in an event or such that requires the disposability, so I guess it's there in case something extra unusual happens. So I'm considering skipping the using var name = ... syntax and let the GC deal with it eventually.
One way or the other, I'd like to have only lambda expression and if it's possible, I can apply disposer too, though, under the condition that it won't require me to create a multi-statement.