.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接口
。请注意,这并不能解决所有问题,因为某些类型可能缺少公共默认构造函数或是泛型类型定义。