LoginSignup
0
0

More than 1 year has passed since last update.

Angularで非シングルトンサービスを作りたい

Posted at

Angularのサービスはシングルトンですが、サービス内でスレッドアンセーフなライブラリを使用している場合等は非シングルトン化したいためそのメモです。

module.tsのprovidersに下記のように設定すればOKです。

app.module.ts
@NgModule({
  declarations: [
    ...
  ],
  imports: [
    ...
  ],
  // 下記のように、都度新しいインスタンスを返却するようなFactoryを記載
  providers: [
    {
      // どういう名前でDIさせるか
      provide: NotSingletonService,
      useFactory: () => {
        return new NotSingletonService();
      },
      deps: [],
    },
  ],
})

ちなみに、useFactoryでインスタンス化したServiceがさらにDIで他クラスをコンストラクタインジェクションしている場合は下記のように書けばOKです

app.module.ts
@NgModule({
  declarations: [
    ...
  ],
  imports: [
    ...
  ],
  // useFactoryにDIしたい依存サービスを渡せばOK
  providers: [
    {
      provide: NotSingletonService,
      useFactory: (s1: DependencyService1, s2: DependencyService2) => {
        return new NotSingletonService(s1, s2);
      },
      deps: [],
    },
  ],
})

以上です。
あんまり使うシーンはないかもです。

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