将依赖注入与工厂模式混合在一起好吗?
想知道将依赖注入与工厂模式混合是否好?我会在运行时创建不同类型的对象,并在 DI 适合注入东西的地方使用它们,因此可以在工厂构造中注入,例如传递连接字符串或其他东西?
谢谢。
Would like to know if its good to mix dependency injection with the factory patterns ? I would create differents kind of object at runtime and use them where DI is good to inject stuff so it is ok to inject in the factory construction such passing connection string or something ?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
实际上这很常见。如果您需要按需提供某个类的实例,您将注入一个工厂而不是一个特定的对象。但是,您应该使用容器来构造这些对象(如果需要构造其他对象),以保持模式并且不创建依赖项。
It's quite common actually. If you need instances of a certain class on demand, you'll inject a factory instead of a specific object. You should be using the container to construct those objects however (if it needs other objects to be constructed), to stay in the pattern and don't create dependencies.
绝对地!您甚至可以将对象注入您的工厂!
Absolutely! You can even inject objects into your factories!