How to inject a “runtime” dependency like a logged in user which is not available at application boot time?

只谈情不闲聊 提交于 2019-12-06 08:53:13

Instead of bending DI over backwards to supply the User, use an EventBus to fire an event when the user logs in.

If you absolutely must use DI for this and the presenters that require the User aren't used until properly initialized with a non-null User you can defer your call to GWT.create(MyGinjector.class) until after the User is logged in. You would then have two such calls in your application: one for the login code path and a second for the rest of the application.

You could use the Provider interface.

class Presenter {
  @Inject
  Presenter(Provider<User> userProvider) {
     User user = userProvider.get();
  }
}

class UserProvider implements Provider<User> {
  public User user;
  User get() {
    return user;
  }
}

Then your module would have a provider binding like this:

bind(User.class).toProvider(UserProvider.class);

EDIT: To set the user variable, client code could obtain the instance of the UserProvider class via a binding like this:

bind(UserProvider.class).in(Singleton.class);

...which would allow the client code to do this:

injector.getInstance(UserProvider.class).user = new User(...)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!