I am designing a new system and I want to know what inversion of control (IOC) is,  and more importantly, when to use it. 

Does it have to be implemented with interfaces or can be done with classes?

IoC (see Inversion of Control on Wikipedia) is applicable in cases where a component can not perform a task entirely because it doesn't have some necessary information or functionality.

The simplest example of an IoC pattern would be callback functions in C. For example you can declare the function:

void Iterator(void *list, Func* f)


Which iterates over list applying the f function to each of it's item. The Iterator function doesn't  know how each item will be processed, you just provide a function as an argument, and it processes them.

As the previous example shows, IoC allows you to decouple your program into separate components that don't know about each other. One of the most common versions of IoC is Dependecy Injection.

In Dependency Injection each component must declare a list of dependencies required to perform it's task. At runtime a special component (generally) called an IoC Container performs binding between these components. It tries to provide values for published component dependencies.  

Here is an example in pseudo-code:  

class Foo 
{ 
   <Require Boo>Constructor(Boo boo){ boo.DoSomething } 
}


In this example class Foo has a constructor that requires argument of type Boo to perform some action.

You could create an instance of class Foo using code similar to this:

MyContainer.Create(typeof Foo)


MyContainer - is an IoC Container, which takes care of getting instance of Boo and passing it to the Foo constructor.

In summary, IoC allows you to decouple your program into separate parts. This is good because:


Components can be easily tested independently.
Program complexity can be reduced.
You can switch components to another implementation.


However in some cases, IoC can make code harder to understand.

If you want to see good example of real-world usage of IoC, have a look at Mircosoft Composite UI Application Block and CompositeWPF

I hope my explanation helps you.

Regards,
aku
