Factory method with DI and IoC

后端 未结 6 690
被撕碎了的回忆
被撕碎了的回忆 2020-11-22 15:30

I am familiar with these patterns but still don\'t know how to handle following situation:

public class CarFactory
{
     public CarFactory(Dep1,Dep2,Dep3,De         


        
6条回答
  •  时光说笑
    2020-11-22 15:38

    I answered a similar question some time ago. Basically it's all about your choice. You have to choose between verbosity (which gives you more help from a compiler) and automation, which allows you to write less code but is more prone to bugs.

    This is my answer supporting verbosity.

    And this is also a good answer that supports automation.

    EDIT

    I believe the approach you consider wrong is actually the best. Truth being said, usually there won't so many dependencies in there. I like this approach because it's very explicit and rarely results in runtime errors.

    Alternative way 1:

    This one is bad. It's actually a service locator, which is considered an anti-pattern.

    Alternative way 2

    Like you wrote, it's not easy to use if mixed with IOC containter. However in some case a similar approach (poor man's DI) can be useful.

    All in all, I wouldn't bother having "many" dependencies in your factories. It's a simple, declarative code. It takes seconds to write and can save you hours of struggling with runtime errors.

提交回复
热议问题