Skip to content

Allow querying registrations by passing type parameter to isRegistered #399

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

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions lib/get_it.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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<T extends Object>({Object? instance, String? instanceName});
bool isRegistered<T extends Object>({
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
Expand Down
5 changes: 4 additions & 1 deletion lib/get_it_impl.dart
Original file line number Diff line number Diff line change
Expand Up @@ -1103,11 +1103,14 @@ class _GetItImplementation implements GetIt {
bool isRegistered<T extends Object>({
Object? instance,
String? instanceName,
Type? type,
}) {
if (instance != null) {
return _findFirstFactoryByInstanceOrNull(instance) != null;
} else {
return _findFirstFactoryByNameAndTypeOrNull<T>(instanceName) != null;
return _findFirstFactoryByNameAndTypeOrNull<T>(instanceName,
type: type) !=
null;
}
}

Expand Down
17 changes: 17 additions & 0 deletions test/get_it_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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>(TestClass2());

final bool byGenerics = getIt.isRegistered<TestClass>();
final bool byParam = getIt.isRegistered(type: TestClass);

final bool byGenerics2 = getIt.isRegistered<TestClass2>();
final bool byParam2 = getIt.isRegistered(type: TestClass2);

expect(byParam, byGenerics);
expect(byParam, false);
expect(byParam2, byGenerics2);
expect(byParam2, true);
});
}

class SingletonInjector {
Expand Down