In this article, I continued my series on building CandleWise - A Portfolio Management App using ASP.NET Core 6. I focused on integrating real-time stock data with IHttpClientFactory, a tool for managing HttpClient instances. In my previous article, I built the foundation of my portfolio management app using predefined data. While effective for testing, this approach limited me to static data, which didn't reflect the dynamic nature of stock markets. In this second part, I transformed my application from static to dynamic by integrating with a third-party data provider. This allowed me to fetch real-time stock quotes, providing users with current market data.
With real-time data integration, I designed CandleWise to offer users the up-to-date information they needed for making informed investment decisions. In this guide, I walked through the process of integrating stock market data using a third-party API and IHttpClientFactory, simplifying how I managed HttpClient instances. I covered registering IHttpClientFactory, initializing an HttpClient property, creating a function to fetch real-time stock prices, and building a class structure to efficiently handle API response data.
CandleWise - A Portfolio Management App (Part 1): Environment Setup
CandleWise - Part 2: Integrating a third party API
CandleWise - Part 3: Deploying App to Azure
CandleWise - Part 4: Automating Deployment CI/CD
I found IHttpClientFactory to be a useful tool that I could register and utilize to configure and generate HttpClient instances within my application. The key benefits I discovered included:
I explored several consumption patterns for IHttpClientFactory, such as basic usage, named clients, typed clients, and generated clients. In my sample code, I used System.Text.Json to deserialize JSON content returned in HTTP responses.
I found the "Basic usage" of IHttpClientFactory to be a straightforward and effective approach. I registered the IHttpClientFactory by calling AddHttpClient
in Program.cs
, and then used dependency injection (DI) to request the factory when I needed an HttpClient instance. This approach allowed me to avoid direct instantiations of HttpClient with calls to CreateClient
.
Furthermore, using IHttpClientFactory this way provided me with several benefits, such as automatic management of HttpClient lifetimes, which helped prevent common issues like socket exhaustion. It also provided centralized configuration, which made my code clearer and easier to maintain.
I registered IHttpClientFactory
by calling AddHttpClient
in Program.cs
: