Dagger 2 - injecting multiple objects of same type using @Named not working

ε祈祈猫儿з 提交于 2019-12-07 19:37:37

问题


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.



来源:https://stackoverflow.com/questions/40139428/dagger-2-injecting-multiple-objects-of-same-type-using-named-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!