Choose dependency for injection using Kiwi in Flutter

582 Views Asked by At

I have the following code:

KiwiContainer()
      ..registerFactory((c) => GetOrderListOfItemsUseCase(
          repository: c<ShopRepository>()))

The problem here is that the GetOrderListOfItemsUseCase requires an instance of IProfileRepository which the ShopProfileRepository extends from.

NOTE: IProfleRepository is extended by IUserProfileRepository and IShopProfileRepository.

UPDATE: I have the following factories:

..registerFactory<IShopRepository>((c) => c<ShopRepository>())
..registerFactory<IUserProfileRepository>((c) => c<UserProfileRepository>())

The thing is that I want to dynamically inject the proper dependency for GetUserLocationsUseCase.

..registerFactory(
          (c) => GetUserLocationsUseCase(repository: c<IProfileRepository>()))

how can I inject in the code the proper subtype of IProfileRepository whether it IShopRepository or IUserProfileRepository?

1

There are 1 best solutions below

0
On

If you want to dinamically inject either UserProfileRepository or ShopProfileRepository you should register the one you are going to use via its supertype.

KiwiContainer()
      ..registerFactory<IProfleRepository>((c) => ShopProfileRepository())
      ..registerFactory((c) => GetOrderListOfItemsUseCase(
          repository: c<IProfleRepository>()))

And obtain it via its supertype too, like in the snippet.