https://github.com/leancodepl/spyglass
Dependency injection POC
https://github.com/leancodepl/spyglass
Last synced: about 1 year ago
JSON representation
Dependency injection POC
- Host: GitHub
- URL: https://github.com/leancodepl/spyglass
- Owner: leancodepl
- License: apache-2.0
- Created: 2023-08-28T11:28:51.000Z (almost 3 years ago)
- Default Branch: main
- Last Pushed: 2024-06-30T18:03:09.000Z (almost 2 years ago)
- Last Synced: 2025-03-25T19:21:16.024Z (about 1 year ago)
- Language: Dart
- Size: 367 KB
- Stars: 12
- Watchers: 2
- Forks: 0
- Open Issues: 3
-
Metadata Files:
- Readme: README.md
- Changelog: CHANGELOG.md
- License: LICENSE
Awesome Lists containing this project
README
# Spyglass [WIP]
> Note: This package is in active development and its API might change
> frequently. Currently it's basically functional but might contain frequent
> bugs. It has not yet been thoroughly tested and is missing documentation and
> examples.
Reliable service locator for all your Dart needs.
## Installation & usage
Add the latest `spyglass` to your pubspec and you're ready to go!
```sh
dart pub add spyglass
```
A basic hello world:
```dart
import 'package:spyglass/spyglass.dart';
void main() {
deps.add(Dependency.value(Greeter()));
final greeter = deps.get();
greeter.greet();
}
class Greeter {
void greet() {
print('Hello world!');
}
}
```
Register dependencies:
```dart
// simplest way
deps.add(Dependency.value(SomeService()));
// lazy
deps.add(Dependency(create: (deps) => SomeService()));
// with dispose function
deps.add(
Dependency(
create: (deps) => SomeService(),
dispose: (service) => service.dispose(),
),
);
// with another dependency as parameter
deps.add(
Dependency(
create: (deps) => SomeService(
other: deps.get(),
),
),
);
// live updates on change
deps.add(
Dependency(
create: (deps) => SomeService(
other: deps.get(),
),
when: (deps) => deps.watch(),
update: (deps, service) {
return service..other = deps.get();
},
),
);
// async initialization
deps.add(
Dependency(
create: (deps) async {
final service = SomeService();
await service.ensureInitialized();
return service;
},
),
);
// await other dependencies
deps.add(
Dependency(
create: (deps) async {
final other = deps.getAsync();
return SomeService(
other: other,
);
},
),
);
```
Read & watch changes:
```dart
// sync
SomeService service = deps.get();
// optional
SomeService? service = deps.tryGet();
// asynchronously initialized
SomeService service = await deps.getAsync();
// watch updates
Stream serviceStream = deps.watch();
```