What's the difference between using dependency injection with a container and using a service locator? ...
Will the Antimagic Field spell cause elementals not summoned by magic to dissipate?
Weaponising the Grasp-at-a-Distance spell
A German immigrant ancestor has a "Registration Affidavit of Alien Enemy" on file. What does that mean exactly?
Is there a verb for listening stealthily?
Why did Israel vote against lifting the American embargo on Cuba?
Help Recreating a Table
Why did Bronn offer to be Tyrion Lannister's champion in trial by combat?
What is the difference between 准时 and 按时?
Does traveling In The United States require a passport or can I use my green card if not a US citizen?
Why does my GNOME settings mention "Moto C Plus"?
Why aren't these two solutions equivalent? Combinatorics problem
Does using the Inspiration rules for character defects encourage My Guy Syndrome?
What *exactly* is electrical current, voltage, and resistance?
Why does BitLocker not use RSA?
Is my guitar’s action too high?
Who's this lady in the war room?
Can this water damage be explained by lack of gutters and grading issues?
What kind of equipment or other technology is necessary to photograph sprites (atmospheric phenomenon)
Pointing to problems without suggesting solutions
Why are two-digit numbers in Jonathan Swift's "Gulliver's Travels" (1726) written in "German style"?
What is the ongoing value of the Kanban board to the developers as opposed to management
Coin Game with infinite paradox
What came first? Venom as the movie or as the song?
Are Flameskulls resistant to magical piercing damage?
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 9 hours ago
tom6025222tom6025222
892
892
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.
Reading the question I thought about Adaptive Code via C# by Gary McLean Hall, which aligns pretty well with this answer. It has some good analogies like the service locator being the key to a safe; when handed to a class, it may create dependencies at will that might not be easy to spot.
– Dennis
21 mins ago
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.
Reading the question I thought about Adaptive Code via C# by Gary McLean Hall, which aligns pretty well with this answer. It has some good analogies like the service locator being the key to a safe; when handed to a class, it may create dependencies at will that might not be easy to spot.
– Dennis
21 mins ago
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.
Reading the question I thought about Adaptive Code via C# by Gary McLean Hall, which aligns pretty well with this answer. It has some good analogies like the service locator being the key to a safe; when handed to a class, it may create dependencies at will that might not be easy to spot.
– Dennis
21 mins ago
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 8 hours ago
answered 8 hours ago
Carl RaymondCarl Raymond
51525
51525
Reading the question I thought about Adaptive Code via C# by Gary McLean Hall, which aligns pretty well with this answer. It has some good analogies like the service locator being the key to a safe; when handed to a class, it may create dependencies at will that might not be easy to spot.
– Dennis
21 mins ago
add a comment |
Reading the question I thought about Adaptive Code via C# by Gary McLean Hall, which aligns pretty well with this answer. It has some good analogies like the service locator being the key to a safe; when handed to a class, it may create dependencies at will that might not be easy to spot.
– Dennis
21 mins ago
Reading the question I thought about Adaptive Code via C# by Gary McLean Hall, which aligns pretty well with this answer. It has some good analogies like the service locator being the key to a safe; when handed to a class, it may create dependencies at will that might not be easy to spot.
– Dennis
21 mins ago
Reading the question I thought about Adaptive Code via C# by Gary McLean Hall, which aligns pretty well with this answer. It has some good analogies like the service locator being the key to a safe; when handed to a class, it may create dependencies at will that might not be easy to spot.
– Dennis
21 mins ago
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 3 hours ago
Rowan FreemanRowan Freeman
1,78631835
1,78631835
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