Dagger2:是否有可能基于Android版本注入?

时间:2015-12-14 19:12:19

标签: android dagger-2

我是否有可能使用Dagger2注入基于SDK版本的具体实现?

例如

// MediaPlayerComponent.class
@Component(modules = {MediaPlayerModule.class}
public interface MediaPlayerComponent
{
    void inject(MediaPlayerUI ui)
}

// MediaPlayerUI.java
public class MediaPlayerUI
{
    @Inject
    public MediaPlayer mPlayer;
}

// GingerbreadMediaPlayer.java
public class GingerbreadMediaPlayer extends MediaPlayer {...}

// IceCreamSandwichMediaPlayer.java
public class IceCreamSandwichMediaPlayer extends MediaPlayer {...}

2 个答案:

答案 0 :(得分:3)

是的,只需决定在MediaPlayerModule模块中使用@Provides注释的具体方法中返回哪两个实现,返回通用MediaPlayer

答案 1 :(得分:0)

理论上可以说,我之前没有做过,因为我没有必要,但我认为以下情况可行:

  • 您应该有一个父ApplicationComponent来定义您的应用程序的需求。我们称之为ApplicationComponent。
  • 现在让我们假设您希望API21及更高版本以及21以下的API具有2个不同的依赖关系。您应该创建两个继承自应用程序组件的组件,让我们将它们称为Application21Component和ApplicationBelow21Component。
  • 对于这两个组件中的每一个,您应该有一个不同的ApplicationModule,告诉您应用程序组件如何获取所需的依赖项
  • 在你的应用程序类中," getComponent"的主体功能将类似于以下

    public ApplicationComponent getComponent(){ if (mApplicationComponent == null) { if (Build.VERSION.SDK_INT >= 21) { mApplicationComponent = DaggerApplication21Component.builder() .applicationModule(new ApplicationModule(this)) .build(); } else { mApplicationComponent = DaggerApplicationBelow21Component.builder() .applicationModule(new ApplicationModule(this)) .build(); } } return mApplicationComponent; }