Home >Java >javaTutorial >Dagger 2 Error: 'Cannot Be Provided...' – How to Fix Dependency Injection Issues?
Issue:
Dagger 2 returns the error "com.example.MyDependency cannot be provided [...]" when attempting to access a dependency. This error indicates that Dagger lacks the necessary mechanism to create or provide the specified dependency.
Explanation:
As the error message suggests, Dagger requires one of two methods to provide dependencies:
Fix:
To resolve this issue, ensure that you have either:
Add an @Inject annotated constructor to the class that you wish to use as a dependency.
Example:
class MyDependency { @Inject MyDependency() { /**/ } }
Add the module to the component declaration.
Example:
@Module class MyModule { @Provides MyDependency provideMyDependency() { return new MyDependency(); } } @Component(modules = MyModule.class) interface MyComponent { MyDependency myDependency(); }
Additional Notes:
The above is the detailed content of Dagger 2 Error: 'Cannot Be Provided...' – How to Fix Dependency Injection Issues?. For more information, please follow other related articles on the PHP Chinese website!