❔ Can anyone break down this one-line code for me?
I'm following a tutorial surrounding using HttpClient properly. When adding as a service I noticed a syntax I don't think I've used before and I can't quite make sense of it. I think I understand that I'm setting the base address on the injected but how is it doing it? What is actually doing here?
The parameter is
Thanks.
8 Replies
Is it just that you don't understand what
=>
is?I'm not sure in this context haha. I'm under the impression => is used for lambda declaration and expression based properties. What does it mean in this context?
Okay so
When you call
AddHttpClient
, it gets registered into DI that your custom client is available to be resolved, and how to configure that client. The lambda here is an action to configure the client that you're adding, which gets called when something through DI requests an instance of your client.
So when a class requests a CatalogueService
, the lambda declares here gets called to configure the newly created CatalogueService
.Oh so it's a lamda, I see. I think I'm going to have to read up on lamdas and Actions too. Thank you for your help, you've put me on the right track. 👍
its a lambda
oops i forgot to scroll
and also the
AddHttpClient<T>()
makes use of IHttpClientFactory.CreateClient(nameof(T))
whenever dependency of client gets resolved so it manages client lifetime for you following best practicesbtw the term for this is "typed http client", found here https://learn.microsoft.com/en-us/dotnet/architecture/microservices/implement-resilient-applications/use-httpclientfactory-to-implement-resilient-http-requests#how-to-use-typed-clients-with-ihttpclientfactory
Use IHttpClientFactory to implement resilient HTTP requests
Learn how to use IHttpClientFactory, available since .NET Core 2.1, for creating
HttpClient
instances, making it easy for you to use it in your applications.Was this issue resolved? If so, run
/close
- otherwise I will mark this as stale and this post will be archived until there is new activity.