Skip to content

A prototype of Dependency Injection framework for Dart.

License

Notifications You must be signed in to change notification settings

TedSander/di.dart

 
 

Repository files navigation

Build Status

Dependency Injection (DI) framework

Installation

Add dependency to your pubspec.yaml.

dependencies:
  di: ">=3.3.3 <4.0.0"

Then, run pub install.

Import di.

import 'package:di/di.dart';

Example

import 'package:di/di.dart';

abstract class Engine {
  go();
}

class Fuel {}

class V8Engine implements Engine {
  Fuel fuel;
  V8Engine(this.fuel);

  go() {
    print('Vroom...');
  }
}

class ElectricEngine implements Engine {
  go() {
    print('Hum...');
  }
}

// Annotation
class Electric {
  const Electric();
}

class GenericCar {
  Engine engine;

  GenericCar(this.engine);

  drive() {
    engine.go();
  }
}

class ElectricCar {
  Engine engine;

  ElectricCar(@Electric() this.engine);

  drive() {
    engine.go();
  }
}

void main() {
  var injector = new ModuleInjector([new Module()
      ..bind(GenericCar)
      ..bind(ElectricCar)
      ..bind(Engine, toFactory: (fuel) => new V8Engine(fuel), inject: [Fuel])
      ..bind(Engine, toImplementation: ElectricEngine, withAnnotation: Electric)
  ]);
  injector.get(GenericCar).drive(); // Vroom...
  injector.get(ElectricCar).drive(); // Hum...
}

Contributing

Refer to the guidelines for contributing to AngularDart.

About

A prototype of Dependency Injection framework for Dart.

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages

  • Dart 89.1%
  • JavaScript 8.1%
  • Shell 2.5%
  • CoffeeScript 0.3%