是否可以在Dagger 2中有选择地为组件设置模块?

时间:2015-12-04 10:08:23

标签: java android dependency-injection dagger-2

Caused by: java.lang.IllegalStateException: analyticsModule must be set

我正在构建一个使用模板样式初始化的库。用户可以使用该库有选择地为项目设置模块。它使用Dagger 2作为DI。

但是Dagger 2似乎不允许使用可选模块。不能简单地忽略未设置的模块吗?

1 个答案:

答案 0 :(得分:6)

您可能需要考虑使用Multibindings,它允许用户可选地将依赖项添加到Set<T>Map<K,V>中。这是一个例子:

interface Plugin {
    void install(Application application);
}

@Component({ModuleA.class, ModuleB.class})
interface PluginComponent {
    Set<Plugin> plugins();
}

@Module
class ModuleA {
    @Provides(type = SET) Plugin providFooPlugin() {
        return new FooPlugin();
    }
}

@Module
class ModuleB {
    @Provides(type = SET) Plugin providBarPlugin() {
        return new BarPlugin();
    }
}

在这种情况下,您仍然需要每个模块的实例,即使它未被使用。解决这个问题的一个选择是使用@Provides(type = SET_VALUES),并且让你不会关闭的模块返回Collections.emptySet()。这是一个修改过的例子:

interface Plugin {
    void install(Application application);
}

@Component({ModuleA.class, ModuleB.class})
interface PluginComponent {
    Set<Plugin> plugins();
}

@Module
class ModuleA {
    private final Set<Plugin> plugins;

    ModuleA(Set<Plugin> plugins) {
        this.plugins = plugins;
    }

    @Provides(type = SET_VALUES) Plugin providFooPlugins() {
        return plugins;
    }
}

@Module
class ModuleB {
    @Provides(type = SET) Plugin providBarPlugin() {
        return new BarPlugin();
    }
}

现在,您可以致电:

DaggerPluginComponent.builder()
    .moduleA(new ModuleA(Collections.emptySet())
    .build();

或者:

Set<Plugin> plugins = new HashSet<>();
plugins.add(new AwesomePlugin());
plugins.add(new BoringPlugin());
DaggerPluginComponent.builder()
    .moduleA(new ModuleA(plugins)
    .build();
相关问题