Skip to content Skip to sidebar Skip to footer

Android Ioc Dagger Framework - How To Inject A Nested Field ?

I'm using Dagger for Android for dependency injections. I have a UserService object in a Main Class: public class Main implements Runnable { @Inject UserService service; @Overrid

Solution 1:

It is preferrable to use Constructor Injection in this case. This can be achieved as follows:

Main:

publicclassMainimplementsRunnable {

    privatefinal IUserService service;

    @InjectpublicMain(IUserService service) {
        this.service = service;
    }

    @Overridepublicvoidrun() {
        for (User f : service.getUserByName("toto")) {
            System.out.print(f.getM_Nom());
        }
    }

    publicstaticvoidmain(String[] args) {
        ObjectGraphobjectGraph= ObjectGraph.create(newUserModule());
        Mainm= objectGraph.get(Main.class);
        m.run();
    }
}

UserService:

publicclassUserServiceimplementsIUserService {

    privatefinal RepositoryUser m_Repository;

    @InjectpublicUserService(RepositoryUser repository) {
        m_Repository = repository;
    }

    @Overridepublic List<User> getUserByName(String name) {
        return m_Repository.getAll();
    }
}

RepositoryUser:

publicclassRepositoryUser {

    @Inject
    publicRepositoryUser() {
    }

    /* ... */
}

UserModule:

@Module(injects = Main.class)publicclassUserModule {

    @Provides
    IUserService provideIUserService(UserService userService){
        return userService;
    }
}

Everywhere the @Inject annotation is present on a constructor, Dagger can automatically create an instance of that item. So when you request a RepositoryUser instance in the UserService constructor, Dagger will see the @Inject annotation on RepositoryUser's constructor, and use that to create a new instance. We do not need an @Provides method here.

The IUserService parameter on the Main constructor cannot be instantiated, since it is an interface. Using the provideIUserService method in the module, we tell Dagger that we want it to create a new UserService instance.

We do have an @Inject annotation on the Main constructor, but we request it using ObjectGraph.get(Class<T> clzz). Therefore, we need to add injects = Main.class to our module.

Post a Comment for "Android Ioc Dagger Framework - How To Inject A Nested Field ?"