DryIoc Register接口(interface)的多种实现

标签 dryioc

查看 wiki对于 DryIoc,示例显示的似乎与我需要的相反,我想知道是否可能相反?

Wiki (部分示例)

public interface X {}
public interface Y {}

public class A : X, Y {}
public class B : X, IDisposable {}


// Registers X, Y and A itself with A implementation 
container.RegisterMany<A>();

...

我想做以下事情

container.RegisterMany<X>();

// This would return one implementation each of A and B
container.ResolveMany<X>();

然而,这给出了这个错误:“注册抽象实现类型 X 应该是具体的。也没有 FactoryMethod 可以代替使用。”

这是否可能开箱即用,还是我需要通过从程序集中获取接口(interface)的所有实现并循环遍历并相应地注册来自己实现它?

更新

我发现这个示例对于我的情况来说可能有点简单,但对于上面的示例,@dadhi 提供的代码非常有效。

这里有一个更“复杂”的例子

namespace Assembly.A
{
    interface IImporter { }

    abstract class ImporterBase : IImporter { }
}

namespace Assembly.B
{
    interface IStuffImporter : IImporter { }
    interface IOtherImporter : IImporter { }

    class StuffImporter : ImporterBase, IStuffImporter { }
    class OtherImporter : ImporterBase, IOtherImporter { }
}

namespace Assembly.C
{
    class Program
    {
        void Main()
        {
            var container = new Container();

            container.RegisterMany( new[] { typeof(StuffImporter).Assembly }, type => type.IsAssignableTo(typeof(IImporter)) && type.IsClass && !type.IsAbstract);
            //I would like DryIoc to do the following behind the scenes
            //container.Register<IStuffImporter, StuffImporter>();
            //container.Register<IOtherImporter, OtherImporter>();

            var importers = container.ResolveMany<IImporter>();

            importers.Should().HaveCount(2);
            importers.First().Should().BeOfType<StuffImporter>().And.BeAssignableTo<IStuffImporter>();
            importers.Last().Should().BeOfType<OtherImporter>().And.BeAssignableTo<IOtherImporter>();
        }
    }
}

像这样的东西是否可以开箱即用?或者我需要制作自己的扩展方法等吗? 真的不会有那么大的麻烦,我可能会在短时间内完成它,但是我想知道以供将来引用并学习 DryIoc 容器。提前致谢。 :)

最佳答案

RegisterMany 重载接受程序集和服务类型条件(wiki 中的示例之一):

container.RegisterMany(new[] { typeof(A).Assembly }, 
    serviceTypeCondition: type => type == typeof(X));

上面注册了 A 的汇编中 X 的所有实现。

关于DryIoc Register接口(interface)的多种实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42368192/

相关文章:

c# - 注入(inject) Serilog 时出错 "Prism.DryIoc DryIoc.Microsoft.DependencyInjection6.0.0 "

c# - DryIoc 递归依赖异常与工厂(Func<>)

c# - 用于属性注入(inject)的 DryIOC 容器配置

c# - 使用依赖注入(inject)时避免单例存储库(DryIoc)

xamarin.forms - 将 Lazy<> 与 Prism.DryIoc.Forms 一起使用会产生 "container is garbage collected"异常

c# - DryIoc 与 Serilog - 设置日志记录上下文

c# - 容器放在哪里?

c# - 如何使用 DryIOC 解决使用父层级接口(interface)

c# - 如何解析使用 DryIoc.Container 实现接口(interface)的特定类型(在运行时已知)的实例

logging - 在 DryIoc 容器中注册 ILoggerFactory