views:

68

answers:

2

Hi.

I have interface 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)?

+3  A: 

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();
742
Works fine, but asm.GetTypes() should be filtered to not returns interfaces, as it returns IModule too....GetTypes().Where(t => !t.IsInterface)...
Feryt
@Feryt: I added `where !type.IsAbstract` to the answer (after turning the answer into LINQ). This solves even more than only `!t.IsInterface`. Note that this will not solve all problems, because some types could lack a public default constructor or are a generic type definition.
Steven
+2  A: 

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>();
Joshua Flanagan
Works perfect. Thank you.
Feryt