Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dagger injection in Base Class is a good approach?

I have a Car class which extends Vehicle class, i will be injecting some properties in the vehicle class.
Example EDITED

abstract class Vehicle {
    @Inject
    lateinit var default: Default
}

class Car @Inject constructor(): Vehicle() {

}

In my code everything works fine,

But one thing i need to know is that how the dagger injects the properties in base class or its hierarchy?

is this the proper way of injecting?

can anyone clarify this?

like image 512
Stack Avatar asked Oct 22 '25 07:10

Stack


1 Answers

But one thing i need to know is that how the dagger injects the properties in base class or its hierarchy?

For that you can look at the generated source files. In your case there will be something like that:

class Car_Factory implements Factory<Car> {

  @Override
  public Car get() {
    return provideInstance(
      defaultProvider
    );
  }

  public static Car provideInstance(
    Provider<Default> defaultProvider
  ) {
    Car instance = new Car();

    Vehicle_MembersInjector.injectDefault(instance, defaultProvider.get()); // just instance.default = default here
    return instance;
  }
}

As you can see it will create your instance and then will access it's fields (as long as they are public and writable).

is this the proper way of injecting?

It's not recommended way, as you're exposing the fields, which could be private (or protected), and you enabling someone else outside to modify, which violates encapsulation.

Therefore it's better to use constructor injection in this way:

abstract class Vehicle(protected val default: Default)

class Car @Inject constructor(default: Default) : Vehicle(default)

In this way Dagger will create your instance with already initialized fields, and won't be accessing them

like image 89
GV_FiQst Avatar answered Oct 23 '25 21:10

GV_FiQst



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!