ioc_locator 1.0.0
ioc_locator: ^1.0.0 copied to clipboard
Lightweight IoC / dependency injection service locator with sync and async factories, singletons, named instances, scopes and automatic disposal.
example/ioc_locator_example.dart
import 'package:ioc_locator/ioc_locator.dart';
abstract class GreetingRepository {
String greetingFor(String name);
}
class EnglishGreetingRepository implements GreetingRepository {
@override
String greetingFor(String name) => 'Hello, $name!';
}
class GreetingService {
GreetingService(this.repository);
final GreetingRepository repository;
void greet(String name) => print(repository.greetingFor(name));
}
/// A service that needs asynchronous initialization — think: opening a
/// database, reading a settings file, establishing a connection.
class GreetingLog {
GreetingLog._();
static Future<GreetingLog> open() async {
await Future<void>.delayed(const Duration(milliseconds: 10)); // e.g. file I/O
return GreetingLog._();
}
final List<String> _entries = [];
void add(String name) => _entries.add(name);
Future<void> close() async {
print('greeted ${_entries.length} time(s): ${_entries.join(', ')}');
}
}
final ioc = IocLocator();
Future<void> main() async {
// Register a lazily created singleton for the repository interface, a
// factory for the service that depends on it, and an async singleton —
// its factory starts running right here, at registration.
ioc
..registerSingleton<GreetingRepository>(
(locator) => EnglishGreetingRepository(),
)
..register<GreetingService>(
(locator) => GreetingService(locator.get<GreetingRepository>()),
)
..registerSingletonAsync<GreetingLog>(
(locator) => GreetingLog.open(),
disposeAsync: (log) => log.close(),
);
// One await after registration. From here on every service — the async one
// included — resolves with the plain synchronous get. (Without this await,
// a too-early get<GreetingLog>() would throw IocServiceNotReady.)
await ioc.allReady();
final service = ioc.get<GreetingService>();
service.greet('world');
ioc.get<GreetingLog>().add('world');
// Tear down everything created by the locator, in reverse creation order;
// async disposers are awaited — close() has printed before this returns.
await ioc.dispose();
}