Is it bad to use servicelocation instead of constructor injection to avoid writing loads of factory classes

后端 未结 3 1812
离开以前
离开以前 2020-12-09 13:08

Right now we use DI/IOC and when we need to pass extra parameters to a constructor we use a factory class e.g.

public class EmailSender 
{
    internal Email         


        
3条回答
  •  忘掉有多难
    2020-12-09 13:40

    I'm not quite sure about this strong "it is bad" answer gave by Krzysztof. I think there's some trade-off and preference in there without absolutely categorizing them as bad or good.

    • I don't think it is more superfluous writing those IoC.Resolve() call than writing specific constructors or properties for the injection mechanism.
    • This one, i have to agree that you are tied to a service Locator and you have to set it up before instancing a class. However:
      • You can segregate your service locator with more specific interfaces. Thereby reducing the coupling with a huge service locator for every services of your system
      • Yeah, if you use DI mechanism, you will remove all those IoC.Resolve(), but you would still have to use a kind of container to instantiate your "main" services. The DI has to intercept those calls, no?
      • Your service locator could (should?) be "auto-configurable" or at least, pretty easy to set up.
    • See above the "segregate your service locator with more specific interfaces..." point.

    I think using a service locator is indeed hiding your dependencies inside the class instead of exposing them through constructors. And it is an inconvenient in my opinion because you will not know your class is missing something until the service locator is called without being configured.

    But the DI thing is not free of that kind of code darkness. When you use DI, it is really not obvious to understand how those dependencies just "appeared" (DI magic) in your constructor. By using a SL, you at least can see where those dependencies are coming from.

    But still, when testing a class that expose those dependencies on her constructors, you (almost) can't miss it. That is not the case using a service locator.

    I'm not saying Krzysztof was wrong, because I agree with him for the most. But I'm pretty sure using a service locator is not necessarily a bad "design" and certainly not simply bad.

    Phil

提交回复
热议问题