Skip to content

[Feature Request] Distinguish factories and singletons #263

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
crtl opened this issue Mar 2, 2022 · 2 comments
Closed

[Feature Request] Distinguish factories and singletons #263

crtl opened this issue Mar 2, 2022 · 2 comments

Comments

@crtl
Copy link

crtl commented Mar 2, 2022

Currently there is no way to distinguish factories from singletons.

Use Case:
I am using getIt to manage services / blocs that are available globally, most of them are singletons but some require factories.
When a widget/component creates a bloc it is responsible for disposing it.
Due to the nature of GetIt there is currently no way to distinguish if the retrieved object was created using a factory or singleton which in turn directly ties the container to the code because you have to know what instances are instantiated in what way.

// container.dart

getIt.registerLazySingleton<Test>(() => Test());

getIt.registerFactory<Test2>(() => Test2());


// my_widget.dart

/* ... */

initState() {
  super.initState();

  final test = getIt<Test>();

  // How to know that Test2 was created using a factory to dispose resource when widget disposes?
  final test2 = getIt<Test2>();
}

dispose() {
  test2.dispose();
  super.dispose();
}

Solution

Solution would be to add a method like T Function() GetIt.getFactory<T>() or T GetIt.fromFactory<T>().
This would only be syntactic sugar because of BC we cannot change T GetIt.get<T>() so the method would just show the consumer what happens behind the curtain.

/// Returns an instance [T] 
T fromFactory<T>({String? instanceName}) => get<T>(instanceName: instanceName);

/// Returns factory function for [T]
T Function() getFactory<T>({String? instanceName}) => () => get<T>(instanceName: instanceName);

// Usage

final test2 = getIt.fromFactory<Test2>(); // Now we now test2 is created using a factory and we are responsible for disposing it
@escamoteur
Copy link
Collaborator

Not sure if is a responsebility of get_it. In you case I would add a field bool disposeManually that is set to true by the factory and that you can check in the dispose function. @esDotDev what do you think?

@esDotDev
Copy link
Collaborator

Ya even a simple mixin Factory {} works?

if(test2 is Factory){
  test2.dispose();
}

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

3 participants