Search code examples
javakotlindependency-injectiondagger-2dagger

Dagger - Register class without @Inject with minimal ceremony


Lets say I want to register a class with Dagger that doesn't have the @Inject annotation on the constructor and that also takes dependencies in its constructor.

i.e.

// Java
class MyClass {
    public MyClass(MyDependency dependency) { ... }
}
// Kotlin
class MyClass(private val dependency: MyDependency) { ... }

Is there a way to register this class without having to manually wire the dependencies into the constructor?

// This is how I currently do it. I must list all constructor dependencies
// and then pass them through to the constructor by hand
@Provides
public MyClass getMyClass(MyDependency depdencency) {
    return new MyClass(dependency);
}

// Something like this is how I'd like to do it
// In this case, the class is registered _as if_ it had the @Inject on the constructor
@ProvideEvenWithoutAnInject
public abstract MyClass getMyClass();

Does Dagger offer something like the @ProvideEvenWithoutAnInject annotation shown above?


Solution

  • If you can't put an @Inject annotation on the constructor then Dagger can't create the object for you. You'll need to use a @Provides annotated method with a module or @BindsInstance with your component to add it. (Or as a component dependency from a provision method if you want more extra steps)