Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
.NET-创建实现特定接口的每种类型的实例_.net_Structuremap - Fatal编程技术网

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

.NET-创建实现特定接口的每种类型的实例,.net,structuremap,.net,Structuremap,我有接口IModule和几个实现它的类。 在测试中,我需要创建实现该接口的每个类型(类)的实例。 是否可能(使用StructureMap) 我不熟悉StructureMap。无论如何,您需要有实现IModule的类型列表,然后在列表中创建每种类型的对象 要动态获取类型列表,可以是: var types = from asm in AppDomain.CurrentDomain.GetAssemblies() from type in asm.GetType() where

我有接口
IModule
和几个实现它的类。 在测试中,我需要创建实现该接口的每个类型(类)的实例。
是否可能(使用StructureMap)

我不熟悉StructureMap。无论如何,您需要有实现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();

我不熟悉StructureMap。无论如何,您需要有实现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();

要使用StructureMap执行此操作,请执行以下操作:

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>();
var容器=新容器(x=>x.Scan(Scan=>
{
scan.TheCallingAssembly();//有扫描其他程序集的选项
scan.AddAllTypesOf();
}));
var allInstances=container.GetAllInstances();

要使用StructureMap执行此操作:

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>();
var容器=新容器(x=>x.Scan(Scan=>
{
scan.TheCallingAssembly();//有扫描其他程序集的选项
scan.AddAllTypesOf();
}));
var allInstances=container.GetAllInstances();

工作正常,但是asm.GetTypes()应该被过滤为不返回接口,因为它也返回IModule。。。GetTypes().Where(t=>!t.IsInterface).@Feryt:我添加了
Where!键入.isastract
(将答案转换为LINQ后)。这不仅仅解决了
!t、 i接口
。请注意,这并不能解决所有问题,因为某些类型可能缺少公共默认构造函数或是泛型类型定义。工作正常,但asm.GetTypes()应过滤为不返回接口,因为它也返回IModule。。。GetTypes().Where(t=>!t.IsInterface).@Feryt:我添加了
Where!键入.isastract
(将答案转换为LINQ后)。这不仅仅解决了
!t、 i接口
。请注意,这并不能解决所有问题,因为某些类型可能缺少公共默认构造函数或是泛型类型定义。