How to inject Injector?

后端 未结 4 940
太阳男子
太阳男子 2020-12-13 13:39

Situation: i need lazy dependency instantiation in some FooClass, so i pass Injector to class as a constructor parameter.

private f         


        
4条回答
  •  时光取名叫无心
    2020-12-13 14:17

    The arguments that you probably shouldn't be injecting an instance of Injector are quite valid, but as with any rule there are exceptions.

    I have a factory class that takes in class references for which it needs to provide an instance. The instances aren't necessarily known (really, they are, but there are a lot and there might be more) so I can't make Providers for all of them.

    public class ThingFactory {
        private Injector injector;
    
        @Inject
        ThingFactory(Injector injector) {
            this.injector = injector;
        }
    
        public  T getInstance(Class aClass) {
            return injector.getInstance(aClass);
        }
    }
    

    The real class in my app is extending and overriding another class—that's why this class is basically a passthrough to Guice.

提交回复
热议问题