简体   繁体   English

Dagger:POJO中的场注入

[英]Dagger: Field Injection in POJO

I never tried Guide or other DI library, but trying to use Dagger from square for Android application. 我从未尝试过Guide或其他DI库,但尝试使用Dagger from square for Android应用程序。 It works great for Frgements, but not for POJO. 它适用于Frgements,但不适用于POJO。 The user guide assumes some knowledge on DI as it doesn't explain in greater detail. 用户指南假定有关DI的一些知识,因为它没有更详细地解释。 What should I do to inject restAdapater into my POJO. 我该怎么做才能将restAdapater注入我的POJO。 If I do field injection, with the same code, it works in Fragment. 如果我使用相同的代码进行字段注入,它可以在Fragment中使用。

public class MyApplication extends Application {
    private ObjectGraph objectGraph;

    @Override
    public void onCreate() {
        super.onCreate();
        objectGraph = ObjectGraph.create(new DIModule(this));

    }

    public ObjectGraph objectGraph() {
        return objectGraph;
    }

    public void inject(Object object) {
        objectGraph.inject(object);
    }

    ...
    @Module(entryPoints = { 
    MainActivity.class,  
    .....,
    Auth.class, 
    RestAdapter.class
    })
    static class DIModule {@Provides
        @Singleton
        public RestAdapter provideRestAdapter() {
            return new RestAdapter.Builder().setServer(
                    new Server(Const.BASE_URL)).build();
        }
    }
}

//POJO // POJO

public class Auth {

    @Inject
    RestAdapter restAdapater;


    String Username;
    String Password;

    public String authenticate() {
     ...

     Api api = restAdapater.create(..)  // **restAdapater is null**

     }
}

All the fragments are derived from the below, and DI works fine in them. 所有碎片都来自下面,DI工作正常。 In a recent talk by Eric burke , he explains this is necessary because Android constructs the object. Eric Burke最近的一次演讲中 ,他解释说这是必要的,因为Android构建了对象。

public class BaseFragment extends Fragment {
    @Override
    public void onCreate(Bundle state) {
        super.onCreate(state);

        ((MyApplication) getActivity()
                .getApplication())
                .inject(this);
    }

}

If you create an Auth instance yourself, then Dagger wouldn't be aware of this instance and will not be able to inject the dependencies for you. 如果您自己创建一个Auth实例,那么Dagger就不会知道这个实例,也无法为您注入依赖项。

Since you have already declared Auth.class in the Module entryPoints, you just need to ask ObjectGraph for Auth instance: 由于您已经在Module entryPoints中声明了Auth.class,因此您只需要向ObjectGraph询问Auth实例:

Auth auth = objectGraph.get(Auth.class);

Dagger then would know what is required to provide an instance of Auth, ie inject it with your RestAdapter. 然后Dagger会知道提供Auth实例需要什么,即将它注入RestAdapter。

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

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