使用依赖注入时使用工厂创建多个对象

Tho*_*mas 5 dependency-injection ioc-container inversion-of-control

I am trying to figure out how to create multiple objects when using Dependency Injection. As far as I understand the standard approach is to inject a Factory which is then used to create the objects. The part I struggle with is how the Factory creates the objects. So far I see two possible solutions:

The Factory just uses new() to create the object.

  • Isn't DI supposed to free me of the use of new for non value objects?
  • What happens if the Object to be created has dependencies that could be resolved by the IoC?

Use the Container as Serviclocator

  • solves the problems of just newing objects at the cost of introducing an antipattern or is it no longer an antipattern if the use of the serviclocater is constraind within the factories?

感觉就像我可以解决一个糟糕的解决方案。有什么我想念的东西吗?

编辑当前,我根本不使用Ioc,而是在考虑Ninject。尽管Autofac DelegateFactories听起来很有希望。

Ste*_*ven 2

尽管工厂的接口将在应用程序级别定义,但您通常会在靠近 DI 配置的位置定义该工厂类的实现,从而将其作为组合根的一部分。尽管直接从代码调用容器是服务定位器反模式的实现,但在组合根内部定义的任何代码都只是机制,因此不是服务定位器。只要新建对象或调用容器是在组合根内部(或非常接近)完成的,这不是问题,因为应用程序仍然不会受到任何定位器/容器的影响。

换句话说:使用工厂方法。您是否需要new直接在工厂内放置对象或使用容器,取决于对象。让容器创建对象是更好的选择,特别是当它们有自己的依赖项时,但并非所有对象都可以由容器创建。在这种情况下,您需要恢复操作new。当代码是组合根的一部分而不是应用程序的一部分时,两者都很好。工厂本身可以有自己的依赖项。这应该不是问题。您可以让容器连接工厂实例。