I have a SocketManager
class that contains a Socket
and other fields. All fields except the Socket
can be injected during the composition of the object graph with a DI framework. My idea was to simply build the entire object graph upfront by leaving Socket
empty and set it during runtime. This would allow me to complete the SocketManager
instantiation at one point in the code and use that instance throughout my entire program (as it was already set as an dependency through the DI framework)? Is that the standard way to "inject" runtime dependencies or is it bad practice?
A abstract factory seems to be a bad idea for two reasons: a) it creates a different object everytime b) It requires the runtime parameters at every place where I want to create the object
Let me illustrate my problem:
SocketManager class:
public class SocketManager {
//i'll only receive the socket at runtime
Socket socket;
//this object is available at compile-time and can be injected through the DI container
InjectableObject obj;
}
Somewhere in my code [CodePosition1] I will receive the socket like this :
public class SocketCreator{
SocketManager socketManager; //will be injected through DI container at startup
Socket socket = this.serverSocket.accept();
// at this point the socket manager is fully initialized
socketManager.setSocket(socket);
}
At numerous other places [CodePosition2] I can now use the SocketManager dependency
public class RandomClass {
//injected at compile-time through DI container, but only usable after [CodePosition1]
// was executed
SocketManager socketManager;
...
socketManager.getSocket().doSth()
...
}
The problem is that SocketManager
is not fully initialized, until [CodePosition1] at runtime, so I don't know any other way than using a init() or setter on SocketManager to "complete" the initialization of the SocketManager. This is however a leaky abstraction, as explained in this post: Is there a pattern for initializing objects created via a DI container