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

南楼画角 提交于 2019-11-27 05:48:25

问题


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 EmailSender(string toEmail, string subject,String body, ILogger emailLogger)
    {.....} 
}

public class EmailSenderFactory
{
    ILogger emailLogger;
    public EmailSenderFactory(ILogger emailLogger)
    { 
        this.emailLogger = emailLogger;
    }
    public EmailSender Create(string toEmail, string subject, string body) 
    {
        return new EmailSender(toEmail, subject, body, emailLogger);
    }
}

Now the problem with this is that we end up creating a whole lotta factory classes, and people don't always know to use them (they sometimes new them up themselves). What are the biggest negatives of coding the class like this:

public class EmailSender 
{
    EmailLogger logger = IoC.Resolve<ILogger>();
    internal EmailSender(string toEmail, string subject,String body)
    {.....} 
}

Pro: we now can use the constructor safely without needing a factory class Con: we have to reference the Service Locator (I'm not worried about testability, its easy to use a mock container as the backing service for the container).

Is there some big stinker of a reason out there why we shouldn't do this?

edit: after a bit of thought, I twigged that by having a private constructor, and by nesting the Factory class, I could keep the implementation and factory together, and prevent people from creating classes improperly, so the question has become somewhat moot. All the points points about SL being dirty, are of course true, so the solution below keeps me happy:

public class EmailSender 
{
    public class Factory
    {
        ILogger emailLogger;
        public Factory(ILogger emailLogger)
        { 
            this.emailLogger = emailLogger;
        }
        public EmailSender Create(string toEmail, string subject, string body) 
        {
            return new EmailSender(toEmail, subject, body, emailLogger);
        }
    }
    private EmailSender(string toEmail, string subject,String body, ILogger emailLogger)
    {
    } 
}

回答1:


yes - it is bad.

  • Why write all that code when you can have the framework do the work? All the IoC.Resolve() calls are superfluous and you shouldn't have to write them.
  • Another, even more important aspect, is that your components are tied to your service locator.

    You're now unable to instantiate them just like that - you need a completely set up service locator in place every time you need to use a component.

  • Last but, bot least - your SL code is sprinkled all over your codebase which is not a good thing, because when you want to change something, you have to look in multiple places.



回答2:


The largest reason I can think of (without just looking at issues with Service Locators in general) is that it is not what I as a user of your class would expect.

Meta discussion:
Some DI frameworks (Guice for example) will build the factory for you.

Some people advocate separating the "newable" from the "injectable".




回答3:


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



来源:https://stackoverflow.com/questions/1599811/is-it-bad-to-use-servicelocation-instead-of-constructor-injection-to-avoid-writi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!