ltackmann / dice

Lightweight dependency injection framework for Dart
Other
34 stars 7 forks source link

Allow to register/override injections at runtime #7

Closed ltackmann closed 11 years ago

ltackmann commented 11 years ago

For example create an injector that can inject the current user.

main() {
    var injector = new Injector(new MyModule());
    var loginPage = injector.getInstance(LoginPage);    
}

class LoginPage {
    @Inject
    UserService _userService;
    @Inject
    Injector _injector;

    doLogin(username, password) {
         User user = userService.login(username, password);
         MyModule module = injector.unwrap();
         module.currentUser = user;

         mainPage = injector.getInstance(MainPage);
         naviageTo(mainPage);
    } 

    naviageTo(var page) {
        :
    }    
}

class MyModule extends Module {
   configure() {
      bind(User).toBuilder(() => currentUser);
      bind(MainPage).toType(MainPage);
      bind(LoginPage).toType(LoginPage);
   }

   User currentUser;
}

class MainPage {
  @Inject
   User currentUser;
}
ltackmann commented 11 years ago

Fixed in 7fa385fbf885f4004f1f9084a27c70fc11d37b1e