我有以下架构,其中引用内部 Helper 类的公共(public)服务类存在于另一个程序集中:
ApplicationAssembly {
public class Widget {
public Widget(ReferencedAssembly.Service service) { ... }
}
}
ReferencedAssembly {
public class Service {
public Service(Helper helper) { ... }
}
class Helper { ... }
}
(我意识到我不能将内部类放在公共(public)类的构造函数的参数中——我只是想说明我所追求的 IoC 模式。)
问题是
ApplicationAssembly
看不到 ReferencedAssembly.Helper
,所以它不能在我的 IoC 容器中注册(在这种情况下是 Autofac)。结果,Helper
尝试解决时无法解决Service
.我在这里最好的选择是什么?Helper
来自 Service
的构造函数并在构造函数中显式地新建它。我不喜欢这个选项,因为它有点打破了 IoC 范式。 Helper
实现公共(public)IHelper
接口(interface),然后在 ReferencedAssembly
中添加一个公共(public)模块注册 Helper
作为 IHelper
.我不喜欢这个选项,因为它需要 ApplicationAssembly
了解太多关于 Service
的实现细节,如果用户忘记在启动时注册该模块,一切都会中断。 Service
上创建公共(public)静态构造函数专门为 ReferencedAssembly
构建第二个 IoC 容器并注册 Helper
在里面。删除 Helper
来自 Service
的构造函数并使用第二个 IoC 容器在构造函数中解析它。这似乎是我最好的选择,但需要比其他更多的“管道”代码。我也不是公共(public)静态构造函数的忠实粉丝。 最佳答案
使用 Autofac 注册内部类型的方法是包含 Autofac Module在具有内部类型的程序集内,并将模块注册到容器中。因为模块在同一个程序集中,它可以配置 ContainerBuilder
与内部类型。
我认为最好的选择是制作 Service
实现一个公共(public)接口(interface),然后使 Service
您当前拥有的内部类(class)。 Autofac 会很高兴地实例化一个内部类来提供一个公共(public)接口(interface)。
另一个选项(允许 Service
使构造函数依赖于内部类型)是使 Service
的构造函数内部,然后使用 Service
中的构造函数查找器类型注册:
builder.RegisterType<Service>()
.FindConstructorsWith(new BindingFlagsConstructorFinder(BindingFlags.NonPublic));
关于architecture - 在解析公共(public)类时注入(inject)内部帮助类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4775323/