So I'm trying to create some fluent code to execute a web request. I want it to look something like this...
// Result should be of type MyClass
var result = await _webRequests.Get("Api/Route/Here")
.Returns<MyClass>()
.HasToken("MY_TOKEN")
.ExecuteAsync();
// Result should be of type HttpResponseMessage
var result = await _webRequests.Get("Api/Route/Here")
.HasToken("MY_TOKEN")
.ExecuteAsync();
I'm aiming to get it so that if the Returns method is not specified, then it returns a HttpResponseMessage and if it is specified, it returns the type specified.
_webRequests is an interface with some basic HttpMethod calls in there
IUseRequired Get(string url);
IUseRequired Post(string url);
Then the IUseRequired interface has the required methods for the call...
IUseOptionalOrExecute UsesApi(string apiName);
All the UsesApi method does is tell which HTTPClient to use when using IHttpClientFactory.
Now the IUseOptionalOrExecute interface is where the problem starts...
IUseOptionalOrExecute Returns<TReturn>();
IUseOptionalOrExecute HasToken(string token);
Task<TReturn> ExecuteAsync();
I want it to look something like this, so whatever is passed in to the Returns method will be used as the return of the ExecuteAsync method. Of course this doesn't work, because ExecuteAsync has no idea what TReturn is. I've thought about storing the type as a variable when the Returns method is called, but I can't set the return type of Execute to be a variable type. Or can I? Anyone know a way I can get around this? Thanks!
Is there a good reason for the existence of the Returns<TReturn>
function ?
When I implemented my HTTP client I had the return type specified on the ExecuteAsync<TReturn>
, since there was no need to know the type beforehand and thus I avoided solving you issue.
If you need the type for some reason, I think you might need to do IUseOptionalOrExecute<TReturn> Returns<TReturn>();
and deal with all the necessary complications.
I can expand on that if ExecuteAsync<TReturn>
is not enough to solve your issue.