gpt4 book ai didi

c# - 把容器注入(inject)一个工厂就OK了吗?

转载 作者:行者123 更新时间:2023-11-30 21:09:17 25 4
gpt4 key购买 nike

我正在使用工厂来创建接口(interface)的不同具体实例。具体实例之一取决于通常会注入(inject)的服务。服务的生命周期由容器管理。这种情况下是不是可以把容器注入(inject)工厂?

最佳答案

我会让容器解析抽象工厂、工厂接口(interface)或工厂委托(delegate),并将其注入(inject)消费者。

然后工厂可以将该服务作为依赖项,由工厂解决。

根据评论更新:

If you're injecting the service into the factory, won't the same instance of that service be passed to each object the factory creates?

是的,工厂创建的每个对象都将获得相同的服务实例(这通常是我想要的)。如果这不是您想要的,请将服务工厂注入(inject)工厂。一些容器支持自动解析工厂委托(delegate),所以你可以注入(inject) Func<IFooService> .

But then the life-cycle of the service is bound to the life-cycle of the factory

正如@SebastianWeber 在评论中提到的,这并不是对所有容器的限制。另外,考虑是否重要。您可以选择两个生命周期中最短的一个并将其用于两者。

关于c# - 把容器注入(inject)一个工厂就OK了吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9101070/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com