I'm trying to use Dagger in my android application to simplify dependency injection. It looks like Dagger 2.0 doesn't support constructors that throw exceptions. Is there a solution to this?
It doesn't seem feasible to refactor and create an init method that throws exceptions instead, because having to call init on the entire chain of dependent objects reintroduces the problems that dagger solves.
It's not clear to generated code what should happen when an exception is thrown during a constructor. Should classes that depend on instances of this class be required to catch the exception somehow? Should the application crash if the exception is thrown? In general, Dependency Injection tries to separate the dependent class from knowing the construction strategy of its dependencies and this would violate that principle.
One option is to use a @Module
which @Provides
the instance(s). Then, if the exception is thrown, that @Provides
method can return a sensible default. You could also consider using Optional<>
to indicate that the object could not be constructed correctly.
In some cases you can create the instances separately, implementing your own exception handling, then you can pass them to the module.
Example:
@Module
public class MyModule {
private final Configuration config;
public MyModule(Configuration config) {
this.config = config;
}
@Provides
@Singleton
Configuration configuration() {
return this.config;
}
@Provides
@Singleton
SomethingElse somethingElse(Configuration config) {
return new SomethingElse(config);
}
}
and you pass the instance from outside
try {
config = new Configuration(...);
} catch (...) {}
ServiceComponent serviceComponent = DaggerMonkMain_ServiceComponent.builder()
.myModule(new myModule(config))
.build();
This is only practical if the number of classes that can throw exceptions during creation is small.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With