0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

.NETのDI ライフタイムの種類

Posted at

.NET(ASP.NET Core)のDIでは、サービスを登録するときにライフタイム(インスタンスの生存期間)を次の3種類から指定します。

1. Transient

services.AddTransient<IMyService, MyService>();

毎回新しいインスタンスが生成される** 方式です。
軽い処理・状態を持たないサービスに向いています。

2. Scoped

services.AddScoped<IMyService, MyService>();

スコープごと(ASP.NET Core ではリクエストごと)に インスタンス生成されます。
1リクエスト内では状態を維持したいけど、リクエスト外では維持する必要がないサービスに使用します。

3. Singleton

services.AddSingleton<IMyService, MyService>();

アプリ全体で 1 つのインスタンスを共有します。
設定管理やキャッシュなど、共有されるべきサービスに向いています。

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?