Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are we using IoC effectively?

So my company uses Castle Windsor IoC container, but in a way that feels "off":

  • All the data types are registered in code, not the config file.
  • All data types are hard-coded to use one interface implementation. In fact, for nearly all given interfaces, there is and will only ever be one implementation.
  • All registered data types have a default constructor, so Windsor doesn't instantiate an object graph for any registered types.

The people who designed the system insist the IoC container makes the system better. We have 1200+ public classes, so its a big system, the kind where you'd expect to find a framework like Windsor. But I'm still skeptical.

Is my company using IoC effectively? Is there an advantage to new'ing objects with Windsor than new'ing objects with the new keyword?

like image 299
Juliet Avatar asked Mar 21 '10 21:03

Juliet


1 Answers

The short answer: No, your company isn't using DI effectively.

The slightly longer answer: The main problem is that all classes have default constructors. When that's the case, then how do you resolve dependencies?

Either your constructors have hard-coded dependencies like this:

public Foo()
{
    IBar bar = new Bar();
}

In which case you can't vary the dependencies without recompiling that application.

Even worse, they may use the Static Service Locator anti-pattern:

public Foo()
{
    IBar bar = Container.Resolve<IBar>();
}

A DI Container should resolve the entire dependency graph in the application's Composition Root and get out of the way.

In general it's better to use Convention over Configuration by using a heuristic approach in code to configure the container. XML configuration should be reserved for those few cases where you need to be able to reconfigure dependencies without recompiling, which should only be a small subset. In short, I see no inherent problem with configuring the container in code. In fact, it's the preferred approach.

Having only one implementation per interface is not a problem either. It's a start, and if the application is truly loosely coupled, it's a constantly open window of opportunity. Sooner or later you will be very likely to introduce alternative implementations, but you can best do this if the interfaces are already in place and the entire code base adhere to the Liskov Substitution Principle.

like image 52
Mark Seemann Avatar answered Oct 02 '22 18:10

Mark Seemann