[Feature Request] Distinguish factories and singletons
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
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?
Ya even a simple mixin Factory {} works?
if(test2 is Factory){
test2.dispose();
}