1
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?

More than 3 years have passed since last update.

Flutter TDD Clean Architecture Course その13 - Dependency Injection

Last updated at Posted at 2020-12-27

これまでやったこと

  • CleanArchitectureに沿って以下のクラスをすべて実装完了
    • Domain層
      • Entity
      • UseCase
      • Repository(Interface)
    • Data層
      • Repository(Implement)
      • Model
      • DataSource

今回やること

  • get_itを用いてDependency Injection

get_itを使う

  • ServiceLocatorであるget_itを用いる
  • オブジェクトの注入を行う

サポートするインスタンス作成方法

  • SingletonとFactoryがある
    • 今回はほぼSingletonを使う
      • すべてのclassでState管理をしていないため
  • Presentation logic(BLoC)ではFactoryを使う
    • UIがNavigationにより破棄される際にStreamがcloseされるから
      • StatefulWidgetでdispose()が呼ばれる際
    • BLoCでSingletonを使うと、closeされたStreamを持つインスタンスが使い回されれてしまう

LazySingleton

  • lazyは非同期生成
    • 今回はどちらを使っても特に変わりはない

Repository

  • UseCaseはRepositoryのインターフェイスに依存している
    • DIするオブジェクトを用意に変更できる
injection_container.dart
sl.registerLazySingleton<NumberTriviaRepository>(
  () => NumberTriviaRepositoryImpl(
    remoteDataSource: sl(),
    localDataSource: sl(),
    networkInfo: sl(),
  ),
);

初期化

main.dart
import 'injection_container.dart' as di;

void main() async {
  await di.init();
  runApp(MyApp());
}

学んだこと

  • CleanArchitectureに沿って、オブジェクト間の依存をなくすようにDIの形で実装した
    • このDIをするのが今回のコーディングになる
  • 同じインターフェイスを継承しているクラスのオブジェクトであれば、入れ替えが用意となる
    • TDDをしない場合、Fakeクラスを作り実装を進めることができる
1
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
1
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?