gpt4 book ai didi

dependency-injection - IoC 和动态对象

转载 作者:行者123 更新时间:2023-12-04 08:20:30 26 4
gpt4 key购买 nike

我无法弄清楚如何解析依赖于在运行时非确定性创建的对象的对象。什么是最好的方法?

想象一下类似文字处理器的东西。对于您打开的每个文档,您可能希望创建大量依赖于文档对象的对象。

例如,您想要获取一个 DocumentEditor 的实例:

public class DocumentEditor {
public DocumentEditor(IDocument document,
ISpellChecker spellChecker,
IWordCounter wordCounter) {
...
}
}

到目前为止,我已经考虑过两种方法,但似乎都不合适:

使用被注入(inject)的工厂

这种方法的问题在于,您最终可能会为需要创建的每种类型创建一个工厂。即

public interface ISpellCheckerFactory {
ISpellChecker Create(IDocument document);
}

public interface IWordCounterFactory {
IWordCounter Create(IDocument document);
}

public class DocumentEditorFactory {
public DocumentEditorFactory(ISpellCheckerFactory spellCheckerFactory,
IWordCounterFactory wordCounterFactory) {
...
}

public DocumentEditor Create(IDocument document) {
...
}
}

再添加 50 个类,您就会发现问题...

使用嵌套容器

使用嵌套容器消除了创建无数工厂的需要。它实际上非常紧凑(使用 Unity 的示例):

var child = container.CreateChildContainer();
child.RegisterInstance<IDocument>(theDocument);
child.Resolve<DocumentEditor>();

这种方法的缺点是容器会到处泄漏。

(作为旁注,统一实现这有点棘手。例如:How to register types in the main container, but resolve in a child container?)

混合方法

应该可以通过实现创建嵌套容器并使用子容器解决依赖关系的 DocumentEditorFactory 将两者结合起来。

最好的分析瘫痪...

最佳答案

在 autofac 中有一个方法叫做 DelegateFactories .它与您的第一个选项有点相似,但是删除了大量的手动编码。

关于dependency-injection - IoC 和动态对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/796740/

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