What is Inversion of Control? *

Question

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?

Answer

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.

< br > via < a class="StackLink" href=" http://stackoverflow.com/questions/3058/" >What is Inversion of Control?< /a>
Share on Google Plus

About Cinema Guy

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment