Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dagger doesn't like constructors that throw exceptions

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.

like image 226
brnby Avatar asked Dec 13 '15 18:12

brnby


2 Answers

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.

like image 112
rdshapiro Avatar answered Oct 11 '22 19:10

rdshapiro


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.

like image 41
fede1024 Avatar answered Oct 11 '22 19:10

fede1024