2010-05-05 27 views

回答

3

我不熟悉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(); 
+0

做工精細,但asm.GetTypes()應該被過濾以不返回接口,因爲它也返回IModule。 ... GetTypes()。Where(t =>!t.IsInterface)... – Feryt 2010-05-05 10:01:33

+0

@Feryt:我在答案中添加了'where.type.IsAbstract'(將答案轉換爲LINQ後)。這不僅僅解決了'!t.IsInterface'問題。請注意,這不會解決所有問題,因爲某些類型可能缺少公共默認構造函數或者是泛型類型定義。 – Steven 2010-05-05 10:52:12

3

做到這一點使用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

完美的作品。謝謝。 – Feryt 2010-05-06 08:39:58

相關問題