麻烦掌握匕首基础知识

时间:2015-01-19 20:47:20

标签: java android dependency-injection dagger

我正在尝试使用Dagger作为我的Android应用程序的依赖注入库。在我的项目中,我在项目中有不同的Android模块,代表了应用程序的不同风格。我想使用依赖注入来允许每个模块定义自己的导航菜单。

我的MenuFragment类需要我的界面实例(MenuAdapterGenerator):

public class MenuFragment extends Fragment {

    @Inject
    protected MenuAdapterGenerator generator;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
        //this.generator is always null here, though shouldn't it be injected already?:
        BaseExpandableListAdapter adapter = new MenuAdapter(inflater, this.generator);
    }
}

这就是我的菜单模块:

@Module (
    injects = MenuAdapterGenerator.class
)
public class MenuDaggerModule {
    public MenuDaggerModule() {
        System.out.println("test");
    }

    @Provides @Singleton MenuAdapterGenerator provideMenuAdapterGenerator() {
        return new MenuNavAdapterGenerator();
    }

}

以下是整体应用级模块(包括此MenuDaggerModule):

@Module (
    includes = MenuDaggerModule.class,
    complete = true
)
public class OverallAppModule {

}

(编辑:)这是我的MainActivity类,它创建了对象图:

public class MainActivity extends Activity {

private ObjectGraph objGraph;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.objGraph = ObjectGraph.create(OverallAppModule.class);
    this.mainWrapper = new MainWrapper(this, this.objGraph);
    this.setContentView(R.layout.activity_main);
    //Other instantiation logic
}

(编辑:)这里是我实际制作MenuFragment的地方(在MainWrapper中):

public class MainWrapper {

    public MainWrapper(Activity activity, ObjectGraph objGraph) {
        this.menu = new MenuFragment();
        this.objGraph.inject(this.menu);
        //I have no idea what the above line really does
        FragmentManager fm = this.activity.getFragmentManager();
        FragmentTransaction t = fm.beginTransaction();
        t.replace(R.id.menu_fragment, this.menu);
        t.commit();
    }

}

为什么没有调用我的模块提供的MenuAdapterGenerator方法来注入我的MenuAdapterGenerator?如果我在该方法中设置断点,它永远不会被触发。但是MenuDaggerModule正在创建,因为System.out.println(" test");正在被击中。

我的理解是,如果创建MenuDaggerModule(它是),Dagger应该在遇到@Injects MenuAdapterGenerator时使用该provideMenuAdapterGenerator()。我有什么不对?

1 个答案:

答案 0 :(得分:1)

Dagger很有魔力,但 很多。你仍然需要告诉Dagger注入你的实例。

我假设您在MenuFragment中引用了MainActivity。当您创建Fragment时,您需要通过调用ObjectGraph.inject(T)告诉Dagger注入它:

MenuFragment fragment = new MenuFragment();
this.objectGraph.inject(fragment);
Transaction transaction = getFragmentManager().beginTransaction();
// etc.

Dagger现在会注意到@Inject上的MenuAdapterGenerator注释,并致电provideMenuAdapterGenerator()注入它。


我想推荐我的another answer,它讨论了构造函数注入。虽然Fragment是少数情况之一,但这不可能(与ActivityView s一起),您可能需要考虑使用该技术注入可能的其他自定义类。