From 8103b511553676abe6384ace3ea63546264397f3 Mon Sep 17 00:00:00 2001 From: dbck-gsc Date: Thu, 30 Jan 2025 08:25:46 -0700 Subject: [PATCH] Allow querying registrations by passing type parameter to isRegistered --- lib/get_it.dart | 8 ++++++-- lib/get_it_impl.dart | 5 ++++- test/get_it_test.dart | 17 +++++++++++++++++ 3 files changed, 27 insertions(+), 3 deletions(-) diff --git a/lib/get_it.dart b/lib/get_it.dart index 4b0db0d..d3ea055 100644 --- a/lib/get_it.dart +++ b/lib/get_it.dart @@ -450,9 +450,13 @@ abstract class GetIt { bool useWeakReference = false, }); - /// Tests if an [instance] of an object or aType [T] or a name [instanceName] + /// Tests if an [instance] of an object or a Type ([T] or [type]) or a name [instanceName] /// is registered inside GetIt - bool isRegistered({Object? instance, String? instanceName}); + bool isRegistered({ + Object? instance, + String? instanceName, + Type? type, + }); /// In some cases it can be necessary to change the name of a registered instance /// This avoids to unregister and reregister the instance which might cause trouble diff --git a/lib/get_it_impl.dart b/lib/get_it_impl.dart index a63b6da..48ef960 100644 --- a/lib/get_it_impl.dart +++ b/lib/get_it_impl.dart @@ -1103,11 +1103,14 @@ class _GetItImplementation implements GetIt { bool isRegistered({ Object? instance, String? instanceName, + Type? type, }) { if (instance != null) { return _findFirstFactoryByInstanceOrNull(instance) != null; } else { - return _findFirstFactoryByNameAndTypeOrNull(instanceName) != null; + return _findFirstFactoryByNameAndTypeOrNull(instanceName, + type: type) != + null; } } diff --git a/test/get_it_test.dart b/test/get_it_test.dart index 113f50e..9b53c7a 100644 --- a/test/get_it_test.dart +++ b/test/get_it_test.dart @@ -1368,6 +1368,23 @@ void main() { reason: "getIt.reset() did not dispose in reverse order", ); }); + + test('isRegistered queryable by type param', () { + final getIt = GetIt.instance; + + getIt.registerSingleton(TestClass2()); + + final bool byGenerics = getIt.isRegistered(); + final bool byParam = getIt.isRegistered(type: TestClass); + + final bool byGenerics2 = getIt.isRegistered(); + final bool byParam2 = getIt.isRegistered(type: TestClass2); + + expect(byParam, byGenerics); + expect(byParam, false); + expect(byParam2, byGenerics2); + expect(byParam2, true); + }); } class SingletonInjector {