简体   繁体   English

Dagger2-组件保持为应用程序中的静态对象

[英]Dagger2 - Component hold as a static object in Application

In my Application class, I have my singleton Dagger Component as a static object and reach it via its static getter method. 在我的Application类中,我将我的单例Dagger Component作为静态对象,并通过其静态getter方法到达它。

public class MyApp extends Application {

        private static UtilsComponent utilsComponent;

        @Override
        public void onCreate() {
           ......
        }

        public static UtilsComponent getUtilsComponent(){
            if(utilsComponent == null){
                utilsComponent = DaggerUtilsComponent.builder()
                        .formattersModule(new FormattersModule())
                        .build();
            }
            return utilsComponent;
        }
}

What I want to know is that is this the right way to do this? 我想知道的是这是正确的方法吗? Can it cause problems? 会引起问题吗? If so, what are those? 如果是这样,那是什么?

It is ok, but you will not be able to use inject Context- dependent objects in that way. 可以,但是您将无法以这种方式使用注入上下文相关对象。 For component, requiring Context, use non - static accessor in Application class. 对于需要Context的组件,请在Application类中使用非静态访问器。 Speaking more widely, there will be as many components as your want, but if if component provides @Singleton - annotated functionality, lifecycle of component should not be longer that one of feature using it. 概括地说,将有您想要的组件数量,但是如果组件提供@Singleton-带注释的功能,则组件的生命周期不应比使用它的功能之一更长。

It's okayish. 没关系。 But why would you put it in the Application class? 但是为什么要把它放在Application类中呢? Put it in standard singleton class called for example Injector . 将其放在称为Injector标准单例类中。 Still you might want to initialize that singleton in Application which is fine. 仍然您可能想要在Application初始化该单例,这很好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM