Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dagger 2 - How to inject in a class that I don't control the instantiation of its object

I have a class that is linked to another library by just inserting the ".class", so I don't know how to inject a dependency in this class as I'm not the one who is creating the object and the library just instantiate the class with the default constructor.

Example:

This a converter class for Room

public class AttendeeListConverter {

    @TypeConverter
    public List<Attendee> fromJson(String attendeesJson) {
        if (attendeesJson == null) {
            return null;
        }
        return gson.fromJson(attendeesJson, new TypeToken<List<Attendee>>() { }.getType());
    }
}

and I want to inject my Gson singleton instance, but I'm not the one who is creating an object of that converter class, I'm just passing the "AttendeesListConverter.class" and the creation of the object itself is code generated.

like image 456
Ahmed Hegazy Avatar asked Feb 06 '18 10:02

Ahmed Hegazy


1 Answers

I don't think that there is a clean solution if you do neither control the object creation, nor get access to the object instance afterwards.

Given those circumstances the only thing that you could do is grab a component from within your object and let it inject itself.

class Injector {
  public static AppComponent component;
}

class AttendeeListConverter {

  public AttendeeListConverter() {
    AppComponent component = Injector.component
    component.inject(this);
  }
}

// and initialize it in onCreate of your Application

class MyApp extends Application {
  @Inject AppComponent appComponent;

  onCreate() {
    // ...setup...

    Injector.component = appComponent
  }
}

You could of course also store the component statically in the application itself, or some people also like to store the application in a static variable, so that you could use MyApp.appComponent.inject() instead.

like image 161
David Medenjak Avatar answered Oct 04 '22 04:10

David Medenjak