Skip to content

Commit

Permalink
Merge pull request #363 from hughesjs/get-all-docs
Browse files Browse the repository at this point in the history
Added documentation for getAll
  • Loading branch information
escamoteur authored Apr 22, 2024
2 parents ad618bf + 65ab55d commit 386c6a4
Showing 1 changed file with 34 additions and 0 deletions.
34 changes: 34 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,40 @@ void registerLazySingleton<T>(FactoryFunc<T> func)

You have to pass a factory function `func` that returns an instance of an implementation of `T`. Only the first time you call `get<T>()` this factory function will be called to create a new instance. After that, you will always get the same instance returned.

### Registering multiple implementations

There are certain circumstances where you might wish to register multiple implementations of the same interface and then get a list of all of the relevant implementations later on. For instance, you might have a modular design where each module registers an interface defining a page and then all of these get injected into your navigation bar in your main layout without your layout needing to know about each module.

> [!NOTE]
> To avoid this being a breaking change and to prevent you from erroneously re-registering a type without expecting this behaviour, to enable this you need to call:
>
>```dart
>getIt.enableRegisteringMultipleInstancesOfOneType();
>```
Then, you just register your classes as you normally would:
```dart
getIt.registerLazySingleton<MyBase>(
() => ImplA(),
);
getIt.registerLazySingleton<MyBase>(
() => ImplB(),
);
```
Then, later on you can fetch all instances of this interface by calling:

```dart
final Iterable<MyBase> instances = getIt.getAll<MyBase>();
```
The returned `Iterable` will then contain all registered instances of the requested interface with or without an instance name.
There is also an `async` implementation available for this:

```dart
final Iterable<MyBase> instances = await getIt.getAllAsync<MyBase>();
```

### Overwriting registrations

If you try to register a type more than once you will fail with an assertion in debug mode because normally this is not needed and probably a bug.
Expand Down

0 comments on commit 386c6a4

Please sign in to comment.