Search code examples
design-patternsdependency-injectionservice-locator

Fear of using a Dependency Injection framework


I have been reading up on Dependency Injection frameworks. I really fell in love with the idea of separating the concerns and letting the objects do their core work - which is undoubtedly an excellent and long-standing design principle!

However the more I read on DI frameworks, the more I get worried: 1) In the way they "automagically" resolve dependencies 2) About the extreme complexities being introduced in the configuration files

On just the point #2, I have seen my customers spend millions of dollars to train the people on products of which the significant part was how "not" to touch config files. The administrators are now dreading these config files.

Nevertheless, I see another pattern called Service Locators where I could nicely assemble all the "global" services that I want at the start of my application (may be an application host or app context or whatever). Make this service locator globally available and voila!

However I see that there will be less flexibility when using the Service Locator approach when I need more than one type of "global" service based on some criterion (known to whom?)!

So, here I am more confused than before on which direction to take. Though I like the design principle very much, the complexity in the existing frameworks are throwing me off!

Are my concerns genuine? Anybody else feel the same? If so, is there any good alternative for such massively overwhelming "frameworks"?


Solution

  • As Nate mentioned, the "magic" is optional; you can configure everything by hand if you want.

    I'd avoid the configuration files initially (or forever!) and configure the container in code. That tends to be much easier to read and maintain. Much of the time you don't need on-the-fly changes to configuration. Customers can't touch the configuration files because they don't exist.

    Service locators have downsides; for one, they tend to couple your classes to the locator class/framework. A good DI framework will let you use Plain Old Objects; you may only have a single class in your project that actually uses the DI/IoC framework.

    StructureMap and Unity are both pretty simple; give them a try. Start small.

    Here's a really simple example with Unity (including inline configuration):

    using Microsoft.Practices.Unity;
    
    static void Main()
    {
        using (IUnityContainer container = new UnityContainer())
        {
            container.RegisterType<IRobot, MrRoboto>();
    
            Console.WriteLine("Asking Unity container to give us a Model...");
    
            Model model = container.Resolve<Model>();
            model.MoveRobot();
        }
    }
    
    // class Model
    
    public Model(IRobot robot)
    {
        // Unity will hand the constructor an instance of MrRoboto!
    }