Are we using IoC effectively?

前端 未结 4 1833
星月不相逢
星月不相逢 2020-12-29 07:03

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
4条回答
  •  萌比男神i
    2020-12-29 07:42

    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();
    }
    

    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.

提交回复
热议问题