Created
September 30, 2023 20:43
-
-
Save MelbourneDeveloper/f9ec7ca5a9f0af099007b7c294402feb to your computer and use it in GitHub Desktop.
Keyed Services with ioc_container
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'package:ioc_container/ioc_container.dart'; | |
import 'package:test/test.dart'; | |
///Example service | |
class BigService { | |
final String name; | |
BigService(this.name); | |
Future<void> callApi() => Future<void>.delayed(Duration(seconds: 1)); | |
///We can check equality by the name(key) | |
@override | |
bool operator ==(Object other) { | |
if (identical(this, other)) return true; | |
return other is BigService && other.name == name; | |
} | |
@override | |
int get hashCode => name.hashCode; | |
} | |
///These give us the functionality to add or | |
///access BigService by key | |
extension KeyedExtensions on IocContainer { | |
BigService? keyedBigService(String key) => | |
get<Map<String, BigService>>()[key]; | |
void setBigServiceByKey(String key, BigService service) => | |
get<Map<String, BigService>>()[key] = service; | |
} | |
void main() { | |
test('Keyed Services', () { | |
var count = 0; | |
final builder = (IocContainerBuilder() | |
..add((container) { | |
//Increments the name (key) of the service so they are unique | |
//Uuid would be better | |
count++; | |
var bigService = BigService(count.toString()); | |
bigService; | |
container.setBigServiceByKey(count.toString(), bigService); | |
return bigService; | |
}) | |
..addSingleton( | |
(container) => <String, BigService>{}, | |
)); | |
final container = builder.toContainer(); | |
final bigContainerOne = container<BigService>(); | |
final bigContainerTwo = container<BigService>(); | |
final bigContainerThree = container<BigService>(); | |
//Verifies the three names | |
expect(bigContainerOne.name, '1'); | |
expect(bigContainerTwo.name, '2'); | |
expect(bigContainerThree.name, '3'); | |
//Verifies you can access these by key | |
expect(container.keyedBigService(bigContainerOne.name), bigContainerOne); | |
expect(container.keyedBigService(bigContainerTwo.name), bigContainerTwo); | |
expect( | |
container.keyedBigService(bigContainerThree.name), bigContainerThree); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment