1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

HttpClientをDIで使い回す方法

1
Last updated at Posted at 2025-08-28

はじめに

自分用メモですが、同じ状況の方の参考になれば幸いです。
普段は WPF と ASP.NET の API 開発を長年やっています。
WPFではCommunityToolkit.Mvvmのパッケージを使用しています。

ChatGPTに聞いたこと

「HttpClientはメモリリークの温床になるから使いまわせ」っていうけど、DIで使用するにはSingletonで登録すればいいの?

ChatGPTの答え

「IHttpClientFactory を使いなさい」 とのことでした。
こんな便利な仕組みが用意されているなんて、本当に衝撃でした。しかもNuGetでMicrosoft.Extensions.Httpを入れれば、.NET Standard 2.0 や .NET Framework 4.8 でも利用できるのです。

設定方法1

設定のやり方はこんな感じです。

var services = new ServiceCollection();

// HttpClientFactory + DelegatingHandler 登録
services.AddHttpClient(client =>
  {
      client.BaseAddress = new Uri("https://xxxxxxx.xx.xx");
  });

このように設定すると、DIから HttpClient を取得した際、内部的にプールされ再利用される HttpClient が利用されます。

設定方法2

さらに AddHttpClient を用いると、指定したクラスに対して依存性注入を行った場合のみ、対応する HttpClient が生成されます。

services.AddHttpClient<T>(client =>
  {
      client.BaseAddress = new Uri("https://xxxxxxx.xx.xx");
  });

続きはこちら

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?