❔ Can anyone break down this one-line code for me?

builder.Services.AddHttpClient<CatalogueService>(catalogueClient => { catalogueClient.BaseAddress = new Uri(""); });
builder.Services.AddHttpClient<CatalogueService>(catalogueClient => { catalogueClient.BaseAddress = new Uri(""); });
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
catalogueClient
catalogueClient
but how is it doing it? What is
catalogueClient => { catalogueClient.BaseAddress = new Uri(""); }
catalogueClient => { catalogueClient.BaseAddress = new Uri(""); }
actually doing here? The parameter is
Action<HttpClient> configureClient
Action<HttpClient> configureClient
Thanks.
8 Replies
Thinker
Thinker2y ago
Is it just that you don't understand what => is?
DannyRoastBeef㊙
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?
Thinker
Thinker2y ago
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.
DannyRoastBeef㊙
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. 👍
sibber
sibber2y ago
its a lambda oops i forgot to scroll
Florian Voß
Florian Voß2y ago
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 practices
Florian Voß
Florian Voß2y ago
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.
Accord
Accord2y ago
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.
Want results from more Discord servers?
Add your server