Sunday, August 16, 2009

IoC

As I am moving from Java to DotNet, i am re-evaluating IoC containers.

I've been naively using Spring for a while, and unfortunately, missed out on Guice, which, best I can tell is the IoC of my dreams (now lost to me forever, or at least as long as I am on DotNet).

That said, I am growing skeptical of the concept of an IoC container. To take an example from the Guice site. Is this:

public class BillingModule extends AbstractModule {
@Override
protected void configure() {
bind(TransactionLog.class).to(DatabaseTransactionLog.class);
bind(CreditCardProcessor.class).to(PaypalCreditCardProcessor.class);
bind(BillingService.class).to(RealBillingService.class);
}
}
Really so much more awesome than:
  public static void main(String[] args) {
CreditCardProcessor processor = new PaypalCreditCardProcessor();
TransactionLog transactionLog = new DatabaseTransactionLog();
BillingService billingService
= new RealBillingService(creditCardProcessor, transactionLog);
...
}
?

The primary differences -- best I can tell -- are:
  • Without an IoC container, every class ideally announces every dependency via its constructor. This can result in a lot of constructors requiring, e.g.: Loggers, which is, arguably, displeasing aesthetically. This also may not work smoothly with tools that want a no-arg constructor.
  • If your object graph changes, w/o the IoC container, you'd have to change constructors forcing changes to your wiring code before you could compile. With an IoC container, things can, but are not guaranteed, to adapt more magically. You may not be notified that your code is now broken until it fails in run-time.
It is not clear to me that these trade-offs arguing for using an IoC container.

No comments:

Post a Comment