Tuesday, December 24, 2013

Inversion of Control (or IoC) can be quite confusing when it is first encountered.
  1. What is it?
  2. What problems does it solve?
  3. When is it appropriate and when not?
share|improve this question
72 
The problem with most of these answers is the terminology used. What's a container? Inversion? Dependency? Explain it in layman terms without the big words. –  kirk.burleson Sep 16 '10 at 1:30
2 
add comment

18 Answers

up vote300down voteaccepted
The Inversion of Control (IoC) and Dependency Injection (DI) patterns are all about removing dependencies from your code.
For example, say your application has a text editor component and you want to provide spell checking. Your standard code would look something like this:
public class TextEditor
{
    private SpellChecker checker;
    public TextEditor()
    {
        checker = new SpellChecker();
    }
}
What we've done here is create a dependency between the TextEditor and the SpellChecker. In an IoC scenario we would instead do something like this:
public class TextEditor
{
    private ISpellChecker checker;
    public TextEditor(ISpellChecker checker)
    {
        this.checker = checker;
    }
}
Now, the client creating the TextEditor class has the control over which SpellChecker implementation to use. We're injecting the TextEditor with the dependency.
This is just a simple example, there's a good series of articles by Simone Busoli that explains it in greater detail.
share|improve this answer
9 
Good clear example. However, suppose rather than requiring the ISpellChecker interface be passed to the object's constructor, we exposed it as a settable property (or SetSpellChecker method). Would this still constitute IoC? –  chaiguy Dec 20 '08 at 2:36
8 
chainguy1337 - yes it would. Using setters like that is called setter injection as opposed to constructor injection (both dependency injection techniques). IoC is a fairly generic pattern, but dependency injection acheives IoC –  Schneider Aug 29 '09 at 1:25
61 
Despite the many up-votes, this answer is incorrect. Please seemartinfowler.com/articles/injection.html#InversionOfControl. In particular, note the part saying "Inversion of Control is too generic a term, and thus people find it confusing. As a result with a lot of discussion with various IoC advocates we settled on the name Dependency Injection". –  Rogério Apr 2 '10 at 14:10
13 
I agree with @Rogeria. this doesn't explain why it is called the IoC and I am surprised by the number of up votes ;-) –  Pangea Dec 23 '10 at 20:01
6 
I side with @Rogerio and @Pangea. This may be a good example for constructor injection but not a good answer to the original question. IoC, as defined by Fowler, can be realised without using injection of any kind, e.g. by using a service locator or even simple inheritance. –  mtsz Jul 14 '11 at 0:49 
show 5 more comments
Inversion of Control is what you get when your program callbacks, e.g. like a gui program.
For example, in an old school menu, you might have:
print "enter your name"
read name
print "enter your address"
read address
etc...
store in database
thereby controlling the flow of user interaction.
In a GUI program or somesuch, instead we say
when the user types in field a, store it in NAME
when the user types in field b, store it in ADDRESS
when the user clicks the save button, call StoreInDatabase
So now control is inverted... instead of the computer accepting user input in a fixed order, the user controls the order in which the data is entered, and when the data is saved in the database.
Basically, anything with an event loop, callbacks, or execute triggers falls into this category.
share|improve this answer
45 
dont mark this guy down. technically he is correct martinfowler.com/bliki/InversionOfControl.html IoC is a very general principal. Flow of control is "inverted" by dependency injection because you have effectively delegated dependancies to some external system (e.g. IoC container) –  Schneider Aug 29 '09 at 1:51
15 
Agreed with Schneider's comment. 5 downvotes? The mind boggles, since this is the only answer that's really correct. Note the opening: 'like a gui program.' Dependency injection is only the most commonly-seen realization of IoC. –  Jeff Sternal Feb 12 '10 at 14:45 
9 
Indeed, this is one of the few correct anwsers! Guys, IoC is not fundamentally about dependencies. Not at all. –  Rogério Apr 2 '10 at 14:08
5 
This is confusing. –  kirk.burleson Sep 16 '10 at 1:22
1 
+1 - This is a good description (with example) of the following statement by Martin Fowler - "Early user interfaces were controlled by the application program. You would have a sequence of commands like "Enter name", "enter address"; your program would drive the prompts and pick up a response to each one. With graphical (or even screen based) UIs the UI framework would contain this main loop and your program instead provided event handlers for the various fields on the screen. The main control of the program was inverted, moved away from you to the framework." –  Ashish Gupta Oct 16 '10 at 8:29
show 2 more comments
What is Inversion of Control?
If you follow these simple two steps, you have done inversion of control:
  1. Separate what-to-do part from when-to-do part.
  2. Ensure that when part knows as little as possible about what part; and vice versa.
There are several techniques possible for each of these steps based on the technology/language you are using for your implementation.
--
The inversion part of the Inversion of Control (IoC) is the confusing thing; because inversion is the relative term. The best way to understand IoC is to forget about that word!
--
Examples
  • Event Handling. Event Handlers (what-to-do part) -- Raising Events (when-to-do part)
  • Interfaces. Component client (when-to-do part) -- Component Interface implementation (what-to-do part)
  • xUnit fixure. Setup and TearDown (what-to-do part) -- xUnit frameworks calls to Setup at the beginning and TearDown at the end (when-to-do part)
  • Template method design pattern. template method when-to-do part -- primitive subclass implementation what-to-do part
  • DLL container methods in COM. DllMain, DllCanUnload, etc (what-to-do part) -- COM/OS (when-to-do part)
share|improve this answer
12 
this is a fantastic answer; rather than just giving an example it explains the actual concepts. Thank you! – Philip Potter Jan 16 '11 at 5:32
 
I agree. Nice explanation in simple words. –  Sandeep G B Mar 4 '11 at 13:52 
6 
This is a far, far better answer than the originally accepted answer. –  Travis Jul 8 '11 at 19:40
3 
+1 for this: The inversion part of the Inversion of Control (IoC) is the confusing thing; because inversion is the relative term. The best way to understand IoC is to forget about that word! –  TheSilverBullet Dec 11 '12 at 8:09
add comment

4 comments:

oakleyses said...

louis vuitton handbags, oakley sunglasses, louboutin, longchamp outlet, nike shoes, louis vuitton outlet stores, chanel handbags, burberry outlet, prada outlet, jordan shoes, tiffany and co, michael kors outlet, tory burch outlet, louis vuitton outlet, longchamp handbags, nike free, true religion jeans, michael kors outlet, kate spade outlet, polo ralph lauren outlet, tiffany and co, prada handbags, polo ralph lauren outlet, michael kors outlet, michael kors outlet, longchamp handbags, oakley sunglasses, ray ban sunglasses, kate spade handbags, burberry outlet, louis vuitton outlet, louboutin outlet, louboutin, coach factory outlet, air max, air max, coach outlet, gucci outlet, christian louboutin shoes, michael kors outlet, coach purses, ray ban sunglasses, michael kors outlet, louis vuitton, coach outlet store online, true religion jeans, oakley sunglasses cheap

oakleyses said...

ralph lauren, lululemon, air max, hollister, north face, nike air max, polo lacoste, vanessa bruno, timberland, vans pas cher, louboutin, louis vuitton, oakley pas cher, air max pas cher, nike roshe run, air max, true religion outlet, barbour, sac longchamp, air force, hollister, sac louis vuitton, nike free, polo ralph lauren, nike trainers, louis vuitton uk, nike roshe, sac hermes, longchamp, michael kors, sac burberry, sac guess, mulberry, new balance pas cher, converse pas cher, sac louis vuitton, hogan outlet, nike tn, north face, true religion outlet, ray ban pas cher, michael kors, air jordan, nike blazer, nike free pas cher, michael kors pas cher, abercrombie and fitch, ray ban sunglasses

oakleyses said...

mac cosmetics, mont blanc, marc jacobs, canada goose outlet, nike huarache, vans shoes, soccer jerseys, hollister, giuseppe zanotti, beats by dre, abercrombie and fitch, longchamp, insanity workout, celine handbags, bottega veneta, ghd, nfl jerseys, north face outlet, chi flat iron, ugg boots, birkin bag, ugg australia, canada goose, herve leger, ugg pas cher, rolex watches, valentino shoes, canada goose uk, canada goose, ferragamo shoes, canada goose, ugg boots, uggs outlet, north face jackets, soccer shoes, asics running shoes, new balance shoes, p90x, lululemon outlet, canada goose jackets, mcm handbags, instyler, babyliss pro, ugg, wedding dresses, jimmy choo outlet, reebok outlet, nike roshe run

oakleyses said...

parajumpers, karen millen, air max, converse, pandora charms, moncler, louboutin, moncler, links of london, lancel, juicy couture outlet, oakley, hollister, pandora charms, supra shoes, thomas sabo, canada goose, gucci, wedding dresses, timberland boots, swarovski crystal, air max, coach outlet store online, moncler, ray ban, canada goose, moncler, ugg, louis vuitton, swarovski, hollister, montre homme, moncler, hollister clothing store, ralph lauren, rolex watches, moncler outlet, moncler, iphone 6 cases, baseball bats, juicy couture outlet, toms shoes, vans, pandora jewelry, ugg, converse shoes