What's the difference between using dependency injection with a container and using a service locator? Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern)Dependency Injection/IoC container practices when writing frameworksHow to use Dependency Injection in conjunction with the Factory patternDependency injection and ease of useFor DI, where to create dependencies (new objects) specifically within framework code?Gradually move codebase to dependency injection containerAmbient dependency injection through static service locatorDependencyInjection - Constructor over-injection smell vs service locator - where is the proper approach?Service locator vs Dependency Injection?IoC configurations - one file/assembly in solution or one file per executing assembly?Handling disposables with dependency injection
Why is one lightbulb in a string illuminated?
Unix AIX passing variable and arguments to expect and spawn
Why did Israel vote against lifting the American embargo on Cuba?
Raising a bilingual kid. When should we introduce the majority language?
Determine the generator of an ideal of ring of integers
Should man-made satellites feature an intelligent inverted "cow catcher"?
What is the evidence that custom checks in Northern Ireland are going to result in violence?
How to leave only the following strings?
What documents does someone with a long-term visa need to travel to another Schengen country?
Does using the Inspiration rules for character defects encourage My Guy Syndrome?
Why are two-digit numbers in Jonathan Swift's "Gulliver's Travels" (1726) written in "German style"?
How to produce a PS1 prompt in bash or ksh93 similar to tcsh
What could prevent concentrated local exploration?
Coin Game with infinite paradox
tabularx column has extra padding at right?
How to ask rejected full-time candidates to apply to teach individual courses?
Weaponising the Grasp-at-a-Distance spell
How to charge percentage of transaction cost?
Why do people think Winterfell crypts is the safest place for women, children & old people?
Who can become a wight?
How to create a command for the "strange m" symbol in latex?
Are Flameskulls resistant to magical piercing damage?
Has a Nobel Peace laureate ever been accused of war crimes?
Does Prince Arnaud cause someone holding the Princess to lose?
What's the difference between using dependency injection with a container and using a service locator?
Announcing the arrival of Valued Associate #679: Cesar Manara
Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern)Dependency Injection/IoC container practices when writing frameworksHow to use Dependency Injection in conjunction with the Factory patternDependency injection and ease of useFor DI, where to create dependencies (new objects) specifically within framework code?Gradually move codebase to dependency injection containerAmbient dependency injection through static service locatorDependencyInjection - Constructor over-injection smell vs service locator - where is the proper approach?Service locator vs Dependency Injection?IoC configurations - one file/assembly in solution or one file per executing assembly?Handling disposables with dependency injection
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;
I understand that directly instantiating dependencies inside a class is considered bad practise. This makes sense as doing so tightly couples everything which in turn makes testing very hard.
Almost all the frameworks I've come across seem to favour dependency injection with a container over using service locators. Both of them seem to achieve the same thing by allowing the programmer to specify what object should be returned when a class requires a dependency.
What's the difference between the two? Why would I choose one over the other?
dependency-injection ioc-containers service-locator
New contributor
add a comment |
I understand that directly instantiating dependencies inside a class is considered bad practise. This makes sense as doing so tightly couples everything which in turn makes testing very hard.
Almost all the frameworks I've come across seem to favour dependency injection with a container over using service locators. Both of them seem to achieve the same thing by allowing the programmer to specify what object should be returned when a class requires a dependency.
What's the difference between the two? Why would I choose one over the other?
dependency-injection ioc-containers service-locator
New contributor
add a comment |
I understand that directly instantiating dependencies inside a class is considered bad practise. This makes sense as doing so tightly couples everything which in turn makes testing very hard.
Almost all the frameworks I've come across seem to favour dependency injection with a container over using service locators. Both of them seem to achieve the same thing by allowing the programmer to specify what object should be returned when a class requires a dependency.
What's the difference between the two? Why would I choose one over the other?
dependency-injection ioc-containers service-locator
New contributor
I understand that directly instantiating dependencies inside a class is considered bad practise. This makes sense as doing so tightly couples everything which in turn makes testing very hard.
Almost all the frameworks I've come across seem to favour dependency injection with a container over using service locators. Both of them seem to achieve the same thing by allowing the programmer to specify what object should be returned when a class requires a dependency.
What's the difference between the two? Why would I choose one over the other?
dependency-injection ioc-containers service-locator
dependency-injection ioc-containers service-locator
New contributor
New contributor
New contributor
asked 7 hours ago
tom6025222tom6025222
592
592
New contributor
New contributor
add a comment |
add a comment |
2 Answers
2
active
oldest
votes
(This is actually a pretty good question.)
When the object itself is responsible for requesting its dependencies, as opposed to accepting them through a constructor, it's hiding some essential information. It's only mildly better than the very tightly-coupled case of using new
to instantiate its dependencies. It reduces coupling because you can in fact change the dependencies it gets, but it still has a dependency it can't shake: the service locator. That becomes the thing that everything is dependent on.
A container that supplies dependencies through constructor arguments gives the most clarity. We see right up front that an object needs both an AccountRepository
, and a PasswordStrengthEvaluator
. When using a service locator, that information is less immediately apparent. You'd see right away a case where an object has, oh, 17 dependencies, and say to yourself, "Hmm, that seems like a lot. What's going on in there?" Calls to a service locator can be spread around the various methods, and hide behind conditional logic, and you might not realize you have created a "God class" -- one that does everything. Maybe that class could be refactored into 3 smaller classes that are more focused, and hence more testable.
Now consider testing. If an object uses a service locator to get its dependencies, your test framework will also need a service locator. In a test, you'll configure the service locator to supply the the dependencies to the object under test -- maybe a FakeAccountRepository
and a VeryForgivingPasswordStrengthEvaluator
, and then run the test. But that's more work than specifying dependencies in the object's constructor. And your test framework also becomes dependent on the service locator. It's another thing you have to configure in every test, which makes writing tests less attractive.
Look up "Serivce Locator is an Anti-Pattern" for Mark Seeman's article about it. If you're in the .Net world, get his book. It's very good.
add a comment |
Imagine you are a worker in a factory that makes shoes.
You are responsible for assembling the shoes and so you'll need a lot of things in order to do that.
- Leather
- Measuring tape
- Glue
- Nails
- Hammer
- Scissors
- Shoe laces
And so on.
You're at work in the factory and you're ready to start. You have list of instructions on how to proceed, but you don't have any of the materials or tools yet.
A Service Locator is like a Foreman that can help you get what you need.
You ask the Service Locator every time you need something, and they go off to find it for you. The Service Locator has been told ahead of time about what you're likely to ask for and how to find it.
You'd better hope that you don't ask for something unexpected though. If the Locator hasn't been informed ahead of time about a particular tool or material, they won't be able to get it for you, and they will just shrug at you.
A Dependency Injection (DI) Container is like a big box that gets filled with everything that everyone needs at the start of the day.
As the factory starts up, the Big Boss known as the Composition Root grabs the container and hands out everything to the Line Managers.
The Line Managers now have what they need to conduct their duties for the day. They take what they have and pass what is needed to their subordinates.
This process continues, with dependencies trickling down the line of production. Eventually a container of materials and tools shows up for your Foreman.
Your Foreman now distributes exactly what you need to you and other workers, without you even asking for them.
Basically, as soon as you show up for work, everything you need is already there in a box waiting for you. You didn't need to know anything about how to get them.
add a comment |
Your Answer
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "131"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
tom6025222 is a new contributor. Be nice, and check out our Code of Conduct.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fsoftwareengineering.stackexchange.com%2fquestions%2f390755%2fwhats-the-difference-between-using-dependency-injection-with-a-container-and-us%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
2 Answers
2
active
oldest
votes
2 Answers
2
active
oldest
votes
active
oldest
votes
active
oldest
votes
(This is actually a pretty good question.)
When the object itself is responsible for requesting its dependencies, as opposed to accepting them through a constructor, it's hiding some essential information. It's only mildly better than the very tightly-coupled case of using new
to instantiate its dependencies. It reduces coupling because you can in fact change the dependencies it gets, but it still has a dependency it can't shake: the service locator. That becomes the thing that everything is dependent on.
A container that supplies dependencies through constructor arguments gives the most clarity. We see right up front that an object needs both an AccountRepository
, and a PasswordStrengthEvaluator
. When using a service locator, that information is less immediately apparent. You'd see right away a case where an object has, oh, 17 dependencies, and say to yourself, "Hmm, that seems like a lot. What's going on in there?" Calls to a service locator can be spread around the various methods, and hide behind conditional logic, and you might not realize you have created a "God class" -- one that does everything. Maybe that class could be refactored into 3 smaller classes that are more focused, and hence more testable.
Now consider testing. If an object uses a service locator to get its dependencies, your test framework will also need a service locator. In a test, you'll configure the service locator to supply the the dependencies to the object under test -- maybe a FakeAccountRepository
and a VeryForgivingPasswordStrengthEvaluator
, and then run the test. But that's more work than specifying dependencies in the object's constructor. And your test framework also becomes dependent on the service locator. It's another thing you have to configure in every test, which makes writing tests less attractive.
Look up "Serivce Locator is an Anti-Pattern" for Mark Seeman's article about it. If you're in the .Net world, get his book. It's very good.
add a comment |
(This is actually a pretty good question.)
When the object itself is responsible for requesting its dependencies, as opposed to accepting them through a constructor, it's hiding some essential information. It's only mildly better than the very tightly-coupled case of using new
to instantiate its dependencies. It reduces coupling because you can in fact change the dependencies it gets, but it still has a dependency it can't shake: the service locator. That becomes the thing that everything is dependent on.
A container that supplies dependencies through constructor arguments gives the most clarity. We see right up front that an object needs both an AccountRepository
, and a PasswordStrengthEvaluator
. When using a service locator, that information is less immediately apparent. You'd see right away a case where an object has, oh, 17 dependencies, and say to yourself, "Hmm, that seems like a lot. What's going on in there?" Calls to a service locator can be spread around the various methods, and hide behind conditional logic, and you might not realize you have created a "God class" -- one that does everything. Maybe that class could be refactored into 3 smaller classes that are more focused, and hence more testable.
Now consider testing. If an object uses a service locator to get its dependencies, your test framework will also need a service locator. In a test, you'll configure the service locator to supply the the dependencies to the object under test -- maybe a FakeAccountRepository
and a VeryForgivingPasswordStrengthEvaluator
, and then run the test. But that's more work than specifying dependencies in the object's constructor. And your test framework also becomes dependent on the service locator. It's another thing you have to configure in every test, which makes writing tests less attractive.
Look up "Serivce Locator is an Anti-Pattern" for Mark Seeman's article about it. If you're in the .Net world, get his book. It's very good.
add a comment |
(This is actually a pretty good question.)
When the object itself is responsible for requesting its dependencies, as opposed to accepting them through a constructor, it's hiding some essential information. It's only mildly better than the very tightly-coupled case of using new
to instantiate its dependencies. It reduces coupling because you can in fact change the dependencies it gets, but it still has a dependency it can't shake: the service locator. That becomes the thing that everything is dependent on.
A container that supplies dependencies through constructor arguments gives the most clarity. We see right up front that an object needs both an AccountRepository
, and a PasswordStrengthEvaluator
. When using a service locator, that information is less immediately apparent. You'd see right away a case where an object has, oh, 17 dependencies, and say to yourself, "Hmm, that seems like a lot. What's going on in there?" Calls to a service locator can be spread around the various methods, and hide behind conditional logic, and you might not realize you have created a "God class" -- one that does everything. Maybe that class could be refactored into 3 smaller classes that are more focused, and hence more testable.
Now consider testing. If an object uses a service locator to get its dependencies, your test framework will also need a service locator. In a test, you'll configure the service locator to supply the the dependencies to the object under test -- maybe a FakeAccountRepository
and a VeryForgivingPasswordStrengthEvaluator
, and then run the test. But that's more work than specifying dependencies in the object's constructor. And your test framework also becomes dependent on the service locator. It's another thing you have to configure in every test, which makes writing tests less attractive.
Look up "Serivce Locator is an Anti-Pattern" for Mark Seeman's article about it. If you're in the .Net world, get his book. It's very good.
(This is actually a pretty good question.)
When the object itself is responsible for requesting its dependencies, as opposed to accepting them through a constructor, it's hiding some essential information. It's only mildly better than the very tightly-coupled case of using new
to instantiate its dependencies. It reduces coupling because you can in fact change the dependencies it gets, but it still has a dependency it can't shake: the service locator. That becomes the thing that everything is dependent on.
A container that supplies dependencies through constructor arguments gives the most clarity. We see right up front that an object needs both an AccountRepository
, and a PasswordStrengthEvaluator
. When using a service locator, that information is less immediately apparent. You'd see right away a case where an object has, oh, 17 dependencies, and say to yourself, "Hmm, that seems like a lot. What's going on in there?" Calls to a service locator can be spread around the various methods, and hide behind conditional logic, and you might not realize you have created a "God class" -- one that does everything. Maybe that class could be refactored into 3 smaller classes that are more focused, and hence more testable.
Now consider testing. If an object uses a service locator to get its dependencies, your test framework will also need a service locator. In a test, you'll configure the service locator to supply the the dependencies to the object under test -- maybe a FakeAccountRepository
and a VeryForgivingPasswordStrengthEvaluator
, and then run the test. But that's more work than specifying dependencies in the object's constructor. And your test framework also becomes dependent on the service locator. It's another thing you have to configure in every test, which makes writing tests less attractive.
Look up "Serivce Locator is an Anti-Pattern" for Mark Seeman's article about it. If you're in the .Net world, get his book. It's very good.
edited 6 hours ago
answered 6 hours ago
Carl RaymondCarl Raymond
42525
42525
add a comment |
add a comment |
Imagine you are a worker in a factory that makes shoes.
You are responsible for assembling the shoes and so you'll need a lot of things in order to do that.
- Leather
- Measuring tape
- Glue
- Nails
- Hammer
- Scissors
- Shoe laces
And so on.
You're at work in the factory and you're ready to start. You have list of instructions on how to proceed, but you don't have any of the materials or tools yet.
A Service Locator is like a Foreman that can help you get what you need.
You ask the Service Locator every time you need something, and they go off to find it for you. The Service Locator has been told ahead of time about what you're likely to ask for and how to find it.
You'd better hope that you don't ask for something unexpected though. If the Locator hasn't been informed ahead of time about a particular tool or material, they won't be able to get it for you, and they will just shrug at you.
A Dependency Injection (DI) Container is like a big box that gets filled with everything that everyone needs at the start of the day.
As the factory starts up, the Big Boss known as the Composition Root grabs the container and hands out everything to the Line Managers.
The Line Managers now have what they need to conduct their duties for the day. They take what they have and pass what is needed to their subordinates.
This process continues, with dependencies trickling down the line of production. Eventually a container of materials and tools shows up for your Foreman.
Your Foreman now distributes exactly what you need to you and other workers, without you even asking for them.
Basically, as soon as you show up for work, everything you need is already there in a box waiting for you. You didn't need to know anything about how to get them.
add a comment |
Imagine you are a worker in a factory that makes shoes.
You are responsible for assembling the shoes and so you'll need a lot of things in order to do that.
- Leather
- Measuring tape
- Glue
- Nails
- Hammer
- Scissors
- Shoe laces
And so on.
You're at work in the factory and you're ready to start. You have list of instructions on how to proceed, but you don't have any of the materials or tools yet.
A Service Locator is like a Foreman that can help you get what you need.
You ask the Service Locator every time you need something, and they go off to find it for you. The Service Locator has been told ahead of time about what you're likely to ask for and how to find it.
You'd better hope that you don't ask for something unexpected though. If the Locator hasn't been informed ahead of time about a particular tool or material, they won't be able to get it for you, and they will just shrug at you.
A Dependency Injection (DI) Container is like a big box that gets filled with everything that everyone needs at the start of the day.
As the factory starts up, the Big Boss known as the Composition Root grabs the container and hands out everything to the Line Managers.
The Line Managers now have what they need to conduct their duties for the day. They take what they have and pass what is needed to their subordinates.
This process continues, with dependencies trickling down the line of production. Eventually a container of materials and tools shows up for your Foreman.
Your Foreman now distributes exactly what you need to you and other workers, without you even asking for them.
Basically, as soon as you show up for work, everything you need is already there in a box waiting for you. You didn't need to know anything about how to get them.
add a comment |
Imagine you are a worker in a factory that makes shoes.
You are responsible for assembling the shoes and so you'll need a lot of things in order to do that.
- Leather
- Measuring tape
- Glue
- Nails
- Hammer
- Scissors
- Shoe laces
And so on.
You're at work in the factory and you're ready to start. You have list of instructions on how to proceed, but you don't have any of the materials or tools yet.
A Service Locator is like a Foreman that can help you get what you need.
You ask the Service Locator every time you need something, and they go off to find it for you. The Service Locator has been told ahead of time about what you're likely to ask for and how to find it.
You'd better hope that you don't ask for something unexpected though. If the Locator hasn't been informed ahead of time about a particular tool or material, they won't be able to get it for you, and they will just shrug at you.
A Dependency Injection (DI) Container is like a big box that gets filled with everything that everyone needs at the start of the day.
As the factory starts up, the Big Boss known as the Composition Root grabs the container and hands out everything to the Line Managers.
The Line Managers now have what they need to conduct their duties for the day. They take what they have and pass what is needed to their subordinates.
This process continues, with dependencies trickling down the line of production. Eventually a container of materials and tools shows up for your Foreman.
Your Foreman now distributes exactly what you need to you and other workers, without you even asking for them.
Basically, as soon as you show up for work, everything you need is already there in a box waiting for you. You didn't need to know anything about how to get them.
Imagine you are a worker in a factory that makes shoes.
You are responsible for assembling the shoes and so you'll need a lot of things in order to do that.
- Leather
- Measuring tape
- Glue
- Nails
- Hammer
- Scissors
- Shoe laces
And so on.
You're at work in the factory and you're ready to start. You have list of instructions on how to proceed, but you don't have any of the materials or tools yet.
A Service Locator is like a Foreman that can help you get what you need.
You ask the Service Locator every time you need something, and they go off to find it for you. The Service Locator has been told ahead of time about what you're likely to ask for and how to find it.
You'd better hope that you don't ask for something unexpected though. If the Locator hasn't been informed ahead of time about a particular tool or material, they won't be able to get it for you, and they will just shrug at you.
A Dependency Injection (DI) Container is like a big box that gets filled with everything that everyone needs at the start of the day.
As the factory starts up, the Big Boss known as the Composition Root grabs the container and hands out everything to the Line Managers.
The Line Managers now have what they need to conduct their duties for the day. They take what they have and pass what is needed to their subordinates.
This process continues, with dependencies trickling down the line of production. Eventually a container of materials and tools shows up for your Foreman.
Your Foreman now distributes exactly what you need to you and other workers, without you even asking for them.
Basically, as soon as you show up for work, everything you need is already there in a box waiting for you. You didn't need to know anything about how to get them.
answered 1 hour ago
Rowan FreemanRowan Freeman
1,73631835
1,73631835
add a comment |
add a comment |
tom6025222 is a new contributor. Be nice, and check out our Code of Conduct.
tom6025222 is a new contributor. Be nice, and check out our Code of Conduct.
tom6025222 is a new contributor. Be nice, and check out our Code of Conduct.
tom6025222 is a new contributor. Be nice, and check out our Code of Conduct.
Thanks for contributing an answer to Software Engineering Stack Exchange!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fsoftwareengineering.stackexchange.com%2fquestions%2f390755%2fwhats-the-difference-between-using-dependency-injection-with-a-container-and-us%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown