Thursday, April 07, 2005

DITC - Dependency Injection Thru Context

I recently read Cedric Beust's blog where he stated he's not getting the inversion of control containers. This got me thinking. Everyone (well many anyways) are talking about inversion of control (IoC) and dependency injection, but most implementations Ive seen assumes we want the base object injected directly!

Why not mix the Service Locator pattern and dependency injection by injecting a context to the given bean or object? The context semantics are much like the java:comp/env component in J2EE for an EJB, you can only lookup beans on which you depend.

When injected (preferably thru constructor injection), the bean is free to lookup the specific implementation for any interface, on which the bean depend, using the injected context. This could be as simple as:

public interface BeanContext
Object lookup(Class interfaceClass);
Object loookup(Class interfaceClass, Object selector);

public MyBean(BeanContext ctx) {
OtherBeanInterface obi = ctx.lookup(OtherBeanInterface.class);

By injecting the context, we avoid using a direct service locator paradigm, and by using the context as a service locator, the program should be more debugable. Also, and this is where my "design" pays of, is the possibility to add some sort of event listening scheme to the context, thus allowing the users of a context, to be notified when eg. a configuration-changed-event has occoured. This could spawn a re-lookup of the service in which the local bean depends, getting a brand new instance without destroying the current bean, since it HAS to be injected thru the constructor directly..

Well read this and give it some thoughts.....


Post a Comment

<< Home