zone_di 1.0.0 copy "zone_di: ^1.0.0" to clipboard
zone_di: ^1.0.0 copied to clipboard

Dependency injection with a functional API that works without code generation, mirrors or passing around Injector objects.

example/main.dart

/// Example of how a server side framework might use this package to pass
/// configuration and dependencies around via dependency injection.
///
/// Class names borrowed from [Aqueduct](https://aqueduct.io).
library zone_di.example;

import 'package:zone_di/zone_di.dart';

//
// Persistence layer interface
//

final persistentStoreToken =
    Token<PersistentStore>('zone_di.example.persistentStoreToken');

abstract class PersistentStore {}

//
// Postgres implementation of persistence layer
//

final databaseCredentialsToken =
    Token<DatabaseConfiguration>('zone_di.example.databaseCredentialsToken');

class DatabaseConfiguration {
  DatabaseConfiguration(this.username, this.password);
  final String username;
  final String password;
}

class PostgreSQLPersistentStore implements PersistentStore {
  PostgreSQLPersistentStore() {
    final credentials = inject(databaseCredentialsToken);
    connect(credentials.username, credentials.password);
  }

  void connect(String username, String password) {/* ... */}
}

//
// Bootstrapping
//

class App {
  App() : persistentStore = inject(persistentStoreToken);

  final PersistentStore persistentStore;

  void run() {/* ... */}
}

void main() {
  provideFactories({
    persistentStoreToken: () => PostgreSQLPersistentStore(),
    databaseCredentialsToken: () =>
        DatabaseConfiguration('pschiffmann', 'dolphins')
  }, () {
    final app = App();
    app.run();
  });
}
1
likes
40
pub points
0%
popularity

Publisher

unverified uploader

Dependency injection with a functional API that works without code generation, mirrors or passing around Injector objects.

Repository (GitHub)
View/report issues

License

MIT (LICENSE)

Dependencies

meta

More

Packages that depend on zone_di