An open API service indexing awesome lists of open source software.

https://github.com/leancodepl/spyglass

Dependency injection POC
https://github.com/leancodepl/spyglass

Last synced: about 1 year ago
JSON representation

Dependency injection POC

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();
```