dice 1.1.0 dice: ^1.1.0 copied to clipboard
Lightweight dependency injection framework for Dart.
Dice #
Lightweight dependency injection framework for Dart.
Quick Guide #
- Add the folowing to your pubspec.yaml and run pub install
dependencies:
dice: any
- Create some classes and interfaces to inject
class BillingServiceImpl implements BillingService {
// fields starting with $ and _$ gets injected
CreditCardProcessor _$processor;
Receipt chargeOrder(Order order, CreditCard creditCard) {
if(!_$processor.validate(creditCard)) {
throw new ArgumentError("payment method not accepted");
}
// :
}
}
- Register the type/class bindings in a module
class ExampleModule extends Module {
configure() {
// bind CreditCardProcessor to a singleton
bind(CreditCardProcessor).toInstance(new CreditCardProcessorImpl());
// bind BillingService to a prototype
bind(BillingService).toType(new BillingServiceImpl());
}
}
- Run it
import "package:dice/dice.dart";
main() {
var injector = new Injector(new ExampleModule());
injector.getInstance(BillingService).then((BillingService billingService) {
var creditCard = new CreditCard("VISA");
var order = new Order("Dart: Up and Running");
billingService.chargeOrder(order, creditCard);
});
}
for more information see the example application here.