Dagger 2 - injecting multiple objects of same type

2019-05-29 03:34发布

问题:

My module:

@Module
public class TcpManagerModule {
    private ITcpConnection eventsTcpConnection;
    private ITcpConnection commandsTcpConnection;

    public TcpManagerModule(Context context) {
        eventsTcpConnection = new EventsTcpConnection(context);
        commandsTcpConnection = new CommandsTcpConnection(context);
    }

    @Provides
    @Named("events")
    public ITcpConnection provideEventsTcpConnection() {
        return eventsTcpConnection;
    }

    @Provides
    @Named("commands")
    public ITcpConnection provideCommandsTcpConnection() {
        return commandsTcpConnection;
    }
}

Component:

@Component(modules = TcpManagerModule.class)
public interface TcpManagerComponent {
    void inject(ITcpManager tcpManager);
}

class where injection happens:

public class DefaultTcpManager implements ITcpManager {
    private TcpManagerComponent tcpComponent;

    @Inject @Named("events") ITcpConnection eventsTcpConnection;

    @Inject @Named("commands") ITcpConnection commandsTcpConnection;

    public DefaultTcpManager(Context context){
        tcpComponent = DaggerTcpManagerComponent.builder().tcpManagerModule(new TcpManagerModule(context)).build();
        tcpComponent.inject(this);
    }

    @Override
    public void startEventsConnection() {
        eventsTcpConnection.startListener();
        eventsTcpConnection.connect();
    }
}

When I call startEventsConnection, I get NullPointerException - meaning the injection didn't populate the fields.

I followed the example exactly the way it is on the Docs, what is the issue?

Note: on the builder line

tcpComponent = DaggerTcpManagerComponent.builder().tcpManagerModule(new TcpManagerModule(context)).build();

I have a warning saying "tcpManagerModule is deprecated". I read the answer here about this issue, and its saying

It is safe to say that you can just ignore the deprecation. It is intended to notify you of unused methods and modules. As soon as you actually require / use Application somewhere in your subgraph the module is going to be needed, and the deprecation warning will go away.

So, am I not requiring/using the instances? What is the issue here?

回答1:

You could try changing your Component defining the specific class for injection:

@Component(modules = TcpManagerModule.class)
public interface TcpManagerComponent {
    void inject(DefaultTcpManager tcpManager);
}

So that Dagger knows exactly about DefaultTcpManager.class.