Coffeehouse Post

Single Post Permalink

View Thread: General Programmer Question : how much do you reuse code/classes?
  • User profile image

    , Dr Herbie wrote

    So the reason for it's anti-pattern status is simply that it makes classes harder to re-use compared to Composition Root (because of having a dependency on the service locator).

    This really isn't what I took away from it.  Service locator is an anti-pattern that particularly affects larger systems developed my multiple developers.

    Deep in the object graph created by the IoC container, some developer will have a dependency that is not explicit.  They will need to instantiate an IFoo.  Now suppose another developer no longer needs his IFoo, and removes the code that adds it to the container (not realizing the deep dependency).  Whenever that deep code is run, instantiation of IFoo fails and the result is a bug.

    This is particularly problematic in deep code rarely covered by manual testing.  Such a bug could easily make it into production.

    The solution is to use typed factories.  In Castle Windsor, I used the Typed Factory Facility, which allows me to inject an IFactory<T> to resolve any T.  This makes the dependency explicit.  Then, I wrote a custom resolver that checks the whether that dependency is resolvable before injecting the IFactory<T>.  Because this is a deep check (ensuring the first T can be resolved, and then any IFactory<T> that is injected into it, then the factories injected into those, etc.), no matter how large the dependency graph, I get an immediate error if something deep down cannot resolve.

    (And recall that regular DI will give you all of this for anything you can resolve directly in the constructor.  All that the service locators, or typed factories, give you is for any case where you must resolve something after the object has been constructed.)