Posts

Showing posts with the label httpclient

Service Discovery in .NET

This was ported from my original blog post here . Introduction Service Discovery  is a common pattern in distributed systems, like microservices, where one does not need to know the exact address of a resource, instead we ask some kind of database-backed service to get it for us. This is very useful to prevent hardcoding such addresses, instead they are discovered dynamically at runtime. There may be other functionality, but it may also include checking the health of a service first, or rotating the exact address to return, when there are many possibilities. Service discovery is supported in .NET  since version 8, through the  Microsoft.Extensions.ServiceDiscovery  Nuget package. It's a very simple implementation, which I will cover here, the code is made available under the  Microsoft Aspire repo . More advanced service discovery providers include, to name just a few: Consul Etcd Zookeeper Eureka All of these have libraries available for .NET, for free o...

Named HttpClient Registrations

Introduction You're most likely familiar with HttpClient and its recommended usage , which involves calling one of the overloads of AddHttpClient . One thing that you may or may not have noticed is, even though you call the overload that takes a name for the client, it is not registered in the dependency injection (DI) container as such. So I went out to fix this! So, what we want is that any named clients can be also registered with the DI container, which will allow us to retrieve them by the service type and key: var googleClient = serviceProvider.GetRequiredKeyedService<HttpClient>("Google"); or: public IActionResult Index([FromKeyedServices("Google")] HttpClient googleClient) { ... } So, as of now, the only way to obtain the named client is by using  IHttpClientFactory 's CreateClient method: var googleClient = serviceProvider.GetRequiredService<IHttpClientFactory>().CreateClient("Google"); Which is fine, but just takes some extr...