有条件地解决的实例

问题描述

我正在编写一个编辑器,其中一些对象依赖于某个 IFileFormat 接口的实例。

根据文件扩展名,实际实例是 FileFormat1 类或 FileFormat2 类的实例,两者都实现了 IFileFormat 接口。

我想要依赖于 IFileFormat 的类在 c-tor 中获取实例:

class ClientObj {
     public ClientObj(IFileFormat f) { ... }
}

是否可以根据文件扩展名以某种方式动态注册 IFileFormat? (这是一个字符串值)。请注意,文件扩展名本身是在运行时根据用户选择的文件名确定的。

我知道我可以在 ClientObj c-tor 中注入一个工厂,这可以让我动态确定 IFileFormat,但是以某种方式只依赖于 IFileFormat 实例会很好,不是某个工厂实例。

解决方法

如果您的扩展实现在运行时已知,您可以通过 UseInstance(new FileExt2()) 注册它们的实例。

如果您想事先注册所有已知的扩展,但根据条件选择要注入的扩展,则执行:

container.Register<IFileExt,FileExt1>(setup: Setup.With(condition: req => myCfg.FileExt == "ext1"));
// similar for the rest of implementations

更新

您也可以随时使用 Register 选项IfAlreadyRegistered.Replace 新实现。 (UseInstance 表示默认情况下)。然后也不要忘记使用 Setup.With(asResolutionCall: true) 的原因 https://github.com/dadhi/DryIoc/blob/master/docs/DryIoc.Docs/RulesAndDefaultConventions.md#injecting-dependency-asresolutioncall