karlkfi / inject

Dependency injection library for Go (golang)
Apache License 2.0
80 stars 7 forks source link

Tight coupling between the Pointer and Provider #10

Open rdadbhawala-cmspl opened 6 years ago

rdadbhawala-cmspl commented 6 years ago

I'm not sure if I've read the examples right, but it appears that there may be a tight coupling between the Pointer variable and the Provider. When creating a definition in a graph, it always asks for a Pointer and a Provider. And I can't reuse this definition for a different instance of the same pointer type. What is the pattern for creating multiple instances of the service, each with its own instance of dependency? Do I need to create a new Definition for every instantiation of Service/ Dependency in code?

karlkfi commented 6 years ago

Yes. Each Definition is only constructed once, because each Pointer can only hold one object. If you want two copies of Thing then you can use NewThing as the Provider for both, but you need two Pointers to put the two objects in once they’ve been created.

rdadbhawala-cmspl commented 6 years ago

Pardon my questions, but I'm trying to understand the constraints ... Is there a way to get a Singleton instance of a dependency if I don't have the variable that was passed in the definition?

karlkfi commented 6 years ago

Not easily, no.

The idea is that instead of hardcoding the name of the object as a string (which is equivalent to a “magic number” or enum) you reference the object with a pointer variable which you can then inject into objects that need it using the same construction mechanism. This guarantees type safety at compile time, makes refactoring trivial, and allows usage tracing, increasing maintenanability and reducing “magic”.

karlkfi commented 6 years ago

FWIW, you CAN introspect the graph of objects, but if you don’t have the unique identifier (the pointer) you can only do thinks like get the list of definitions that match or satisfy a specific type.