To create an HttpClient with HttpClientFactory typed in C#, you need to first configure the HttpClientFactory in the Startup class of your web application as shown below:
main.cs132 chars5 lines
In this code snippet, we are configuring the HttpClientFactory to create a typed HttpClient of type IMyTypedHttpClient
. Whenever an instance of IMyTypedHttpClient
is requested, the factory will create an instance of MyTypedHttpClient
.
Next, you need to define your typed HttpClient as shown below:
main.cs515 chars22 lines
In this example, we are defining a typed HttpClient called MyTypedHttpClient
which implements IMyTypedHttpClient
. The constructor of MyTypedHttpClient
takes an instance of HttpClient
which is injected by the HttpClientFactory.
Finally, you can use your typed HttpClient in your logic as shown below:
main.cs352 chars15 lines
In this example, we are using the IMyTypedHttpClient
instance injected via Dependency Injection to call the GetStringAsync
method defined on the IMyTypedHttpClient
interface.
gistlibby LogSnag