How to pass arguments to Hilt module? - android

I started to migrate Dagger application to Hilt, first I'm converting AppComponent to Hilt auto-generated ApplicationComponent. Therefore I've added #InstallIn(ApplicationComponent::class) annotation to each module related to this component.
Now I get the following error:
error: [Hilt] All modules must be static and use static provision
methods or have a visible, no-arg constructor.
It points to this module:
#InstallIn(ApplicationComponent::class)
#Module
class AccountModule(private val versionName: String) {
#Provides
#Singleton
fun provideComparableVersion(): ComparableVersion {
return ComparableVersion(versionName)
}
}
Previously in Dagger, it was possible to pass arguments in the constructor. Looks like Hilt doesn't allow this.
How can I pass arguments to Hilt module?

#InstallIn(ApplicationComponent::class)
#Module
class AccountModule {
#Provides
#Singleton
fun provideComparableVersion(application: Application): ComparableVersion {
return ComparableVersion((application as MyApplication).versionName)
}
}
If you don't want to see MyApplication, then you can use an interface.

Unfortunately for now Dagger Hilt is design using monolithic component, where there's only one Application Component and one Activity Component auto generated by it. Refer to https://dagger.dev/hilt/monolithic.html
Hence the modules for it must be static and use static provision methods or have a visible, no-arg constructor.
If you put an argument to the module, it will error out stating
[Hilt] All modules must be static and use static provision methods or have a visible, no-arg constructor.
From my understanding, you'll trying to get the BuildInfo version number, perhaps the easiest way is to use the provided BuildInfo.VERSION_NAME as below.
#InstallIn(ApplicationComponent::class)
#Module
class AccountModule() {
#Provides
#Singleton
fun provideComparableVersion(): ComparableVersion {
return ComparableVersion(BuildInfo.VERSION_NAME)
}
}
If you like to set it yourselves instead of relying on BuildInfo.VERSION_NAME, you can define static const variable that exist differently across flavour.

Related

How inject dagger non empty constructor module dependencies to hilt

Hilt is not supportting non epmty constructor modules. If we need to migrate partially to Hilt from dagger , how we can inject dependencies from legacy dagger modules having non empty constrctors to hilt components such as HiltViewModel.
// Legacy Dagger module
#Module
public class DaggerModule {
private final Boolean customBoolean;
DaggerModule(Boolean customBoolean) {
this.customBoolean = customBoolean;
}
#Provides
#Singleton
CustomClass provideCustomClass() {
return CustomClass(customBoolean);
}
}
#Module
public class AnotherDaggerModule {
#Provides
#Singleton
AnotherClassDepndsOnCustomClass provideAnotherClass(CustomClass customClass) {
return AnotherClassDepndsOnCustomClass(customClass);
}
}
// Migrated Hilt module
#HiltViewModel
class HiltViewModel #Inject constructor(
  private val anotherClass: AnotherClassDepndsOnCustomClass
) : ViewModel() {
  ...
}
Since we are not using components to pass some custom parameters while initialising modules, is there any solution which I'm not aware already exists?
While running the app, the app crashing with error DaggerModule must be set.
You'll need to refactor.
The documentation on Migrating to Hilt describes this case under the heading "Handling Component Arguments", since instantiable modules would otherwise be treated as component arguments passed through a Builder or Factory:
Hilt components cannot take component arguments because the initialization of the component is hidden from users. [...]
If your component has any other arguments either through module instances passed to the builder or #BindsInstance, read this section on handling those. Once you handle those, you can just remove your #Component.Builder interface as it will be unused.
Under "Component arguments" the Hilt documentation confirms that a refactor is required:
Because component instantiation is hidden when using Hilt, it is not possible to add in your own component arguments with either module instances or #BindsInstance calls. If you have these in your component, you’ll need to refactor your code away from using these.
You can consider some of these structures:
Replacement module / subclassing Modules
In your example, you might need to create a replacement Module that provides a binding for CustomClass. This might be as straightforward as subclassing the Module and providing a public no-arg constructor that provides the super(value) constructor call your module needs. If your Module would only ever get a single value in your graph (but might get a different value in a separate application), then this might be enough.
#Module
public class AdaptedDaggerModule extends DaggerModule {
AdaptedDaggerModule() {
super(true);
}
}
Note that module subclasses are somewhat limited in utility, and should not be used for testing overrides.
Custom subcomponents
However, you also wrote "components are created in respective modules where we need to use" in a comment, and you can continue doing so using custom subcomponents in Hilt, with more comprehensive documentation in javadoc or the main Dagger subcomponent documentation. Because you would create this component through an explicit call to a Builder or Factory, you could provide the Module instance there. Subcomponents inherit bindings from their parent components, so you could avoid specifying your entire list of Modules.
Note that doing this as a subcomponent is mostly valuable when you have a dense tree with multiple references to the instance you're providing in the constructor. If this is simply a matter of combining graph-based constructor arguments with one-off constructor arguments, assisted injection is probably a better option.
/** Subcomponents are usually declared on modules. You can also reuse one you have. */
#Module(subcomponents={YourSubcomponent.class})
public interface IncludeThisInYourHiltModuleList {}
#Subcomponent(modules={DaggerModule.class, AnotherDaggerModule.class})
public interface YourSubcomponent {
AnotherClassDepndsOnCustomClass anotherClass();
#Subcomponent.Builder
interface Builder {
Builder daggerModule(DaggerModule daggerModule); // arbitrary name
YourSubcomponent build(); // arbitrary name
}
}
#HiltViewModel
class HiltViewModel #Inject constructor(
private val yourSubcomponentBuilder: YourSubcomponent.Builder
) : ViewModel() {
fun yourMethod() {
val subcomponent =
yourSubcomponentBuilder.daggerModule(DaggerModule(false)).build()
val anotherClass = subcomponent.anotherClass()
// ...
}
}
Constructor values in Hilt-managed components
The most difficult case would be where your Module would want separate values in each of your Hilt-managed components, e.g. each Activity needing to pass a different constructor argument. In that case you might need to rephrase the customBoolean (or other parameters) as deriving the value from the Activity instance itself. This maintains Hilt's expectation that it can create an Activity component for each Activity instance that Android unpredictably creates or recreates, and it can do so without specifying any other constructor parameters.

Dagger hilt: Difference between annotating a class #Singleton and a provides function #Singleton

My question is pretty simple and straightforward: What is the difference between the two annotations / examples:
Example one
#Singleton
class MySingletonClass() {}
#Module
#InstallIn(FragmentComponent::class)
abstract class MyFragmentModule {
#Provides
fun provideMySingletonClass() = MySingletonClass()
}
Eaxmple two
class MySingletonClass() {}
#Module
#InstallIn(FragmentComponent::class)
abstract class MyFragmentModule {
#Singleton
#Provides
fun provideMySingletonClass() = MySingletonClass()
}
The only difference I know is, that the second example gives me the following error:
error: [Dagger/IncompatiblyScopedBindings] FragmentC scoped with #dagger.hilt.android.scopes.FragmentScoped may not reference bindings with different scopes:
Does that mean, that the #Singleton annotation in example one is simply ignored?
In Example One, your #Singleton annotation is ignored, but only because you are calling the constructor yourself in your #Provides method. Because Dagger doesn't interact with your MySingletonClass constructor, it cannot read or use the annotation.
If your #Singleton class MySingletonClass had an #Inject constructor—even an empty one—then Dagger would be able to interact with it directly as long as you also delete the #Provides fun that would override the constructor detection. Once you've done that, the behavior of #Singleton would be the same in either syntax.
Regarding the error message "error: [Dagger/IncompatiblyScopedBindings] XXX scoped with #YYY may not reference bindings with different scopes": #Andrew The real problem here is that in Example Two you're trying to declare a #Singleton binding in a Module that you install in your FragmentComponent. #Singleton bindings can only happen in a #Singleton component, which in Hilt is SingletonComponent. I don't remember for sure, but I think your Example One (with the edits I described) would work with singleton behavior and without an error, because Dagger would automatically select the appropriate component in the hierarchy to install your MySingletonClass.

whats the difference between #Provide and #Inject in dagger2?

Whats the difference between #Inject and #Provide ?
although both are used for providing dependencies then whats the difference ?
This is covered very well in documentation, #Inject and #Provides are two different ways of introducing dependencies in the dependency graph. they are suited for different use cases
#Inject
Easy to use, simply add #Inject on constructor or property and you are done
It can be used to inject types as well as type properties
In a subjective way it may seem clearer than #Provides to some people
#Provides
If you don't have access to source code of the type that you want to inject then you can't mark its constructor with #Inject
In some situations you may want to configure an object before you introduce it in dependency graph, this is not an option with #Inject
Sometimes you want to introduce an Interface as a dependency, for this you can create a method annotated with #Provides which returns Inteface type
Following are the examples of above three points for #Provides
If you can't access source code of a type
// You can't mark constructor of String with #Inject but you can use #Provides
#Provides
fun provideString(): String {
return "Hello World"
}
Configure an object before introducing in the dependency graph
#Provides
fun provideCar(): Car {
val car = Car()
// Do some configuration before introducing it in graph, you can't do this with #Inject
car.setMaxSpeed(100)
car.fillFuel()
return car
}
Inject interface types in dependency graph
interface Logger { fun log() }
class DiscLogger : Logger{ override fun log() { } }
class MemoryLogger : Logger { override fun log() { } }
#Provides
fun provideLogger(): Logger {
val logger = DiscLogger() \\ or MemoryLogger()
return logger
}
#Inject:- It is used to inject dependencies in class.
#provides:- Required to annotated the method with #provide where actual instance is created.
This has covered in Dagger-2 documentation clearly.
What #Inject can Do:
Use #Inject to annotate the constructor that Dagger should use to
create instances of a class. When a new instance is requested, Dagger
will obtain the required parameters values and invoke this
constructor.
If your class has #Inject-annotated fields but no #Inject-annotated
constructor, Dagger will inject those fields if requested, but will
not create new instances. Add a no-argument constructor with the
#Inject annotation to indicate that Dagger may create instances as
well.
Similarly dagger can create for methods also.
Classes that lack #Inject annotations cannot be constructed by
Dagger.
What #Inject can't Do: and can be used #Provides annotation
Interfaces can’t be constructed.
Third-party classes can’t be annotated.
Configurable objects must be configured!

Dagger 2 : ImagesRepo cannot be provided without #Inject constructor or #Provides

I provide ImagesRepo using RepoModule, ImgesReo depends on RxApiController and SharePreferenceHelper and i am providing these dependencies in RepoModule itself, these dependencies comes from AppModule.
#Module(includes = AppModule.class)
public class RepoModule {
#Provides
#Inject
public ImagesRepo providesImagesRepo(RxApiController rxApiController, SharePreferenceHelper sharePreferenceHelper) {
return new ImagesRepo(rxApiController, sharePreferenceHelper);
}
}
When i try to inject ImagesRepo like this
#Inject
public ImagesRepo imagesRepo;
public MyActivityViewmodelImpl() {
MyApplication.getRepoComponent().inject(this);
}
It shows error if i remove #Inject from constructor of ImagesRepo, I think that i am providing RxApiController and SharePreferenceHelper from RepoModule
#Inject
public ImagesRepo(RxApiController rxApiController, SharePreferenceHelper sharePreferenceHelper) {
super(rxApiController, sharePreferenceHelper);
}
Question is why i am suppose to add #Inject at ImagesRepo constructor, if i am providing dependencies for ImagesRepo in RepoModule itself
To avoid errors and confusion you should make sure to understand what each annotation does. A #Provides method does not need an #Inject annotation. Here, you could even use constructor injection alone, and you wouldn't need the #Provides method (or the module) at all, reducing the amount of boilerplate needed.
As to your specific error, I would guess that you either don't add RepoModule to your component, or that you try to inject your class with the wrong component (that does not have access to RepoModule).
Adding #Inject on the constructor of ImagesRepo will mark it for constructor injection so that Dagger can and will create it for you. There is no need for the module (that you didn't add / component can't access), which is why it will "work" when you do so.
To avoid confusion and errors either use a #Provides method from a module or use constructor injection—preferrably constructor injection which will eliminate the boilerplate, which is one of the reasons why you'd use Dagger in the first place.

Difference between scope in modules and components

What is the difference between the #Singleton annotation on Dagger2 #Component annotated classes, and #Provides annotated methods in modules?
If I have one module in which all methods are annotated with a #Singleton annotation, and a component with the same annotation which includes that module, what is the purpose of this?
#Singleton
#Component(...)
public interface AppComponent {
// ...
}
And
#Provides #Singleton Context provideContext() { return context; }
Annotating the #Provides method (or the class with an #Inject constructor) tells Dagger to implement the actual scoping functionality whereas annotating the component (which is necessary) doesn't have any functionality, but tells Dagger "I allow this component to contain bindings of this scope". Note that you can still have unscoped bindings in a scoped component, but not the other way around.
It's well within the use of a Java annotation to provide documentation to reader, which is what you're probably seeing in your first example. It's useful there so the reader can know the intended use of the class/interface without having to know the mechanism by which its instance is created or managed.

Categories

Resources