Dagger Unsmartness(2): Inheritance

Dagger just simply does the binding based on static types and it doesn’t get into the inheritance complexity at all. So you, again as a developer, have to handle the type casting if necessary.

In the following example, HelloWorld requires to inject a Set<Person>, and a Set<Employee> and Set<Manager> are provided in two modules respectively. Since Dagger doesn’t know both Employee and Manager implement the Person interface, I have to handle the type conversion explicitly in the HelloModule.


public class HelloWorld
{
 @Inject
 Set<Person> persons;

public void run()
 {
 for (Person person : persons)
 {
 System.out.println(person.getInfo());
 }

}

public static void main(String[] args)
 {
 ObjectGraph objectGraph = ObjectGraph.create(new HelloModule());
 HelloWorld app = objectGraph.get(HelloWorld.class);
 app.run();
 }
}


@Module(library = true)
public class EmployeeModule
{
 @Provides(type = Provides.Type.SET_VALUES)
 @Singleton
 Set<Employee> provideEmployee()
 {
 return ImmutableSet.<Employee> of(new Employee("John"), new Employee("Sean"));
 }
}


@Module(library = true)
public class ManagerModule
{
 @Provides(type = Provides.Type.SET_VALUES)
 @Singleton
 Set<Manager> provideManagers()
 {
 return ImmutableSet.<Manager> of(new Manager("Dee"), new Manager("Lee"));
 }
}


@Module(injects = HelloWorld.class, includes = { ManagerModule.class, EmployeeModule.class
})
public class HelloModule
{
 @Provides(type = Provides.Type.SET_VALUES)
 @Singleton
 Set<Person> providePersons(Set<Employee> employees, Set<Manager> managers)
 {
 return Sets.union(employees, managers);//import com.google.common.collect.Sets;
 }
}

Advertisements
This entry was posted in Java, Programming and tagged , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s