Welcome Guest, Not a member yet? Register   Sign In
Poll: D.I. vs Service locator?
You do not have permission to vote in this poll.
yes
37.50%
3 37.50%
no
25.00%
2 25.00%
maybe
37.50%
3 37.50%
Total 8 vote(s) 100%
* You voted for this item. [Show Results]

True D.I. vs service locator.
#6

To clarify on the Service Locator part, the Service Locator usually does return an object instance. Whether the Service Locator instantiates the class itself or simply returns a pre-existing instance doesn't matter (but it could do either).

The Service Locator is used by a class to retrieve any services required. So, using Lonnie's DI example, you would use the Service Locator to retrieve an object which conforms to the App\UserModelInterface, instead of passing the User_model through the User's constructor. You might have a pre-defined interface to the Service Locator (for example, something similar to $this->load->xxx()), but a more modern approach would be to pass the Service Locator through the User's constructor. This shows that DI and a Service Locator aren't mutually exclusive, but if you inject a Service Locator, you still don't know what the User class' dependencies really are without examining the code for calls to the Service Locator, and now the User depends on the Service Locator, too.

The key difference is that a class never needs to be aware that a DI Container is being used. Your application requests objects from the DI Container and maybe can configure the DI Container, but the classes managed by the DI Container don't know the difference between being instantiated and managed by a DI Container vs. being managed and instantiated directly by the application. The Service Locator, on the other hand, becomes a dependency of the class using it, and the class has to understand how to get its other dependencies from the Service Locator. In an ideal world, every dealing with a Service Locator involves enough abstraction that the services supplied by the Service Locator and the Service Locator itself are defined by interfaces, so testing is still viable and you can still change out classes without changing everything that uses it, but in practice it's difficult to make Service Locators interchangeable, and classes that depend on a Service Locator are often tied to that specific implementation.
Reply


Messages In This Thread
True D.I. vs service locator. - by skunkbad - 04-09-2015, 10:19 PM
RE: True D.I. vs service locator. - by dmyers - 04-10-2015, 06:44 AM
RE: True D.I. vs service locator. - by skunkbad - 04-10-2015, 06:59 AM
RE: True D.I. vs service locator. - by dmyers - 04-10-2015, 07:09 AM
RE: True D.I. vs service locator. - by kilishan - 07-26-2015, 08:17 PM
RE: True D.I. vs service locator. - by mwhitney - 07-27-2015, 01:19 PM
RE: True D.I. vs service locator. - by kenjis - 07-27-2015, 02:33 PM
RE: True D.I. vs service locator. - by kilishan - 07-27-2015, 07:30 PM



Theme © iAndrew 2016 - Forum software by © MyBB