代码之家  ›  专栏  ›  技术社区  ›  Feryt

.NET-创建实现特定接口的每个类型的实例

  •  0
  • Feryt  · 技术社区  · 15 年前

    我有接口 IModule 以及实现它的几个类。 在测试中,我需要创建实现该接口的每种类型(类)的实例。 是否可以(使用结构映射)?

    2 回复  |  直到 15 年前
        1
  •  3
  •   Steven    15 年前

    我不熟悉结构图。无论如何,您需要有实现IModule的类型列表,然后在列表中创建每种类型的对象。

    要动态获取类型列表,可以是:

    var types =
        from asm in AppDomain.CurrentDomain.GetAssemblies()
        from type in asm.GetType()
        where !type.IsAbstract
        where typeof(IModule).IsAssignableFrom(type)
        select type;
    

    要实例化类型:

    IModule[] instances = (
        from type in types
        select (IModule)Activator.CreateInstance(type))
        .ToArray();
    
        2
  •  3
  •   Joshua Flanagan    15 年前

    要使用结构映射进行此操作:

    var container = new Container(x => x.Scan(scan =>
    {
        scan.TheCallingAssembly(); // there are options to scan other assemblies
        scan.AddAllTypesOf<IModule>();
    }));
    
    var allInstances = container.GetAllInstances<IModule>();