bootique icon indicating copy to clipboard operation
bootique copied to clipboard

Inflate objects from configuration inside DI

Open andrus opened this issue 2 years ago • 0 comments

The current approach to inflating a factory with configuration is rather verbose:

@Singleton
@Provides
MyType provide(ConfigurationFactory cf, MyOtherType ot) {
    return cf.config(MyTypeFactory.class, "prefix").create(ot);
}

// or, after #345
@Singleton
@Provides
MyType provide(ConfigurationFactory cf) {
    return cf.config(MyTypeFactory.class, "prefix").create();
}

Various "convenience" module superclasses (ConfigModule, BaseModule) do not make it much easier, and only add extra uneeded abstractions. But looks like we can failry easily make configuration-bound objects (of which "factories" is a special case) injectable themselves, either as regular DI objects, or as Providers. The first step in this direction was taken in #345 - injection of other services into such objects has been already implemented. Now need to cut on ConfigurationFactory boilerplate.

Proposed binder syntax:

// config applied to MyTypeImpl
binder.bind(MyType.class).to(MyTypeImpl.class).config("prefix");

// config applied to MyTypeProvider
binder.bind(MyType.class).toProvider(MyTypeProvider.class).config("prefix");

The syntax is rather un-opinionated, and will support any style of binding. E.g. here is an example of a factory that is not a provider, bound to config, an then used to create another object, being injected into a "provides" method:

public void configure(Binder b) {
    binder.bind(MyTypeFactory.class).config("prefix");
}

@Singleton
@Provides
MyType provide(MyTypeFactory f) {
    // if needed, you may customize MyType returned from the factory
    return f.create();
}

andrus avatar Nov 26 '23 21:11 andrus