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

No comments: