5
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

ASP.NET Core の IHttpClientFactory を使うときの注意点

5
Last updated at Posted at 2020-09-14

IHttpClientFactory を使うと、使い方に癖のある HttpClient をいい感じに使えるようにしてくれます。

ASP.NET Core で IHttpClientFactory を使用して HTTP 要求を行う

IHttpClientFactory から CreateClient することで、いい感じに使いまわしたり適切なタイミングで破棄したり色々やってくれるので便利です。名前付きクライアントを使うと、IHttpClientFactory には依存せずに設定した通りに構成された HttpClient が渡されて、もっといい感じになります。

IHttpClientFactory を使う上で重要なのは HttpClient のインスタンスを必要な時に生成して不要になったら手放す(Dispose はしなくていい)という感じで作ることです。

Singleton? 

なので、Singleton クラスに HttpClient を DI したり型指定されたクライアントを DI したりすると台無しになってしまいます。型指定されたクライアントは Transient で DI コンテナに登録されているのに Singleton のクラスに DI すると、ずっと同じインスタンスが使いまわされてしまいます。

例えば以下のように…

// DI コンテナへの登録処理
services.AddHttpClient();
services.AddSingleton<SomeSingleton>();

// SomeSingleton の定義
class SomeSingleton
{
    private readonly HttpClient _httpClient; // 私はいつ開放されるの!?

    public SomeSingleton(HttpClient httpClient)
    {
        _httpClient = httpClient;
    }

    // 省略
}

ということで

なので、IHttpClientFactory を DI するようにするか Singleton じゃなくて Scoped か Transient で管理するようにしましょう。

5
4
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
5
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?