开发者

.NET - create instance of each type that implements specific interface

I have interfac开发者_StackOverflow中文版e IModule and several classes that implements it. In test i need to create instance of each type(class) implementing that interface. Is is possible(with StructureMap)?


I'm not familiar with StructureMap. Anyway you need to have the list of types implementing IModule, then you create an object of each type in the list.

To get the list of types dynamically, it can be:

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

To instantiate the types:

IModule[] instances = (
    from type in types
    select (IModule)Activator.CreateInstance(type))
    .ToArray();


To do it using 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>();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜