Skip to content
This repository was archived by the owner on Dec 6, 2017. It is now read-only.

dart-archive/di.dart

Folders and files

NameName
Last commit message
Last commit date

Latest commit

author
Anting Shen
Aug 8, 2014
eefd517 · Aug 8, 2014
Jul 23, 2014
Dec 1, 2013
Jul 23, 2014
Aug 8, 2014
Jul 23, 2014
Aug 8, 2014
Jul 23, 2014
Jul 23, 2014
Feb 5, 2014
Aug 8, 2014
Apr 9, 2013
Jul 23, 2014
Jul 23, 2014
Dec 20, 2013
Apr 16, 2014
Aug 8, 2014
Jul 23, 2014
Aug 8, 2014
Jul 23, 2014

Repository files navigation

Build Status

Dependency Injection (DI) framework

Installation

Add dependency to your pubspec.yaml.

dependencies:
  di: ">=2.0.0 <3.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(modules: [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.