Binding @Provides method as eager singleton

后端 未结 1 622
孤独总比滥情好
孤独总比滥情好 2021-02-07 13:09

I want to make a binding using a method annotated with @Provides into an eager singleton. I\'ve found bug 216, which suggests this isn\'t possible, but doesn\'t men

相关标签:
1条回答
  • 2021-02-07 13:33

    Why not to use

    bind(Logic.class).toInstance(LogicCreator.create(dep)); 
    //ohh we missing dep
    

    then we can do this

    class LogicProvider implements Provider<Logic> {
    
        private final SomeDep dep;
    
        @Inject
        public LogicProvider(SomeDep dep) {
          this.dep = dep;
        }
    
        @Override
        public Logic get() {
          return LogicCreator.create(dep);
        }
    
    }
    

    and then

    bind(Logic.class).toProvider(LogicProvider.class).asEagerSingleton();
    

    You can even pass SomeDep dep to your provider as Provider<SomeDep> and then call providerDep.get() in LogicCreator.create() that would be a bit more robust.

    0 讨论(0)
提交回复
热议问题