Skip to content

[Question ] registerSingleton dependencies #277

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
abdel-ships-it opened this issue May 27, 2022 · 1 comment
Closed

[Question ] registerSingleton dependencies #277

abdel-ships-it opened this issue May 27, 2022 · 1 comment

Comments

@abdel-ships-it
Copy link

How are we supposed to do this? I'm having a hard time having services registered with registerSingleton depend on each other.

Example

GetIt.I.registerSingleton<UserStateService>(UserStateService());
GetIt.I.registerSingleton<AppViewStateService>(AppViewStateService());

And UserStateService looks like this

class UserStateService {
  final appViewStateService = GetIt.I.get<AppViewStateService>();
}

This throws the following error

I/flutter ( 6537): Exception 'package:get_it/get_it_impl.dart': Failed assertion: line 372 pos 7: 'instanceFactory != null': Object/factory with  type AppViewStateService is not registered inside GetIt.
package:get_it/get_it_impl.dart:372
I/flutter ( 6537): (Did you accidentally do GetIt sl=GetIt.instance(); instead of GetIt sl=GetIt.instance;

This forces me to put AppViewStateService on top of UserStateService, is there no other way to do this? I tried

GetIt.I.registerSingletonWithDependencies<UserStateService>(() => UserStateService(), dependsOn: [AppViewStateService]);
GetIt.I.registerSingleton<AppViewStateService>(AppViewStateService());

But this throws the following error

I/flutter ( 6537): Exception Invalid argument(s): Dependent Type AppViewStateService is not registered in GetIt

For now I'm forced to change the order of registrations, if there's another way please let me know.

@escamoteur
Copy link
Collaborator

you have to register them in the correct sequence. registerSingletonWithDependencies is only helpful if your registration needs to wait on some async initialization of another Singleton.
Also I recommend not to store instances that are registered inside get_it in fields of other objects but always access them over GetIt.I<yourType>()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants