2012-02-01 29 views
2

我想检索一个实例化类的枚举,这些实例化类实现了解决方案文件夹中多个程序集之间的接口。检索实现多个程序集接口的对象

我有以下文件夹结构(如果这使得有义):

Solution 
    -SolutionFolder 
     - Project1 
      - class implementing interface I would like to find 
      - other classes 

     - Project2 
      - class implementing interface I would like to find 
      - other classes 

    -MainProject 
     - classes where my code is running in which I would like to retrieve the list of classes 

因此,如果正在执行的接口是ISettings,那么我想的是界面的IEnumerable<ISettings>引用实例化的对象。

到目前为止,我已经使用反射来检索从一个已知的类名实现接口的类:

IEnumerable<ISettings> configuration = 
       (from t in Assembly.GetAssembly(typeof(CLASSNAME-THAT-IMPLEMENTs-INTERFACE-HERE)).GetTypes() 
       where t.GetInterfaces().Contains(typeof(ISettings)) && t.GetConstructor(Type.EmptyTypes) != null 
       select (ISettings)Activator.CreateInstance(t)).ToList(); 

,但是这是一个单装配和我不会真正知道的类名称。

这可以使用反射来实现还是需要更多的东西?

回答

0

要解决此问题,我将解决方案文件夹中每个项目的后期构建事件设置为将其程序集复制到主项目bin文件夹中的bin文件夹中。

后生成事件设置类似于:

copy "$(TargetPath)" "$(SolutionDir)MainProjectName\bin" 

然后我用下面的检索从这个bin目录汇编文件名(信贷达林对他的解决方案后here):

string[] assemblyFiles = Directory.GetFiles(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "bin"), "*.dll"); 

IEnumerable<ISettings> configuration = assemblyFiles.Select(f => Assembly.LoadFrom(f)) 
       .SelectMany(a => a.GetTypes()) 
       .Where(t => t.GetInterfaces().Contains(typeof(ISettings)) && t.GetConstructor(Type.EmptyTypes) != null) 
       .Select(t => (ISettings)Activator.CreateInstance(t)); 

然后我使用检索实现接口ISettings对象的实现

这使我可以添加更多实现设置的项目,而无需重新编译主项目。

此外,我看到的一个替代方案是使用MEF,其中可以找到介绍here

1

只要你只是谈论加载到AppDomain中的程序集(他们将必须为了做你以后做的事情),你可以使用类似这样的方法遍历它们:

AppDomain.CurrentDomain 
     .GetAssemblies().ToList() 
     .ForEach(a => /* Insert code to work with assembly here */); 

或者,如果你有他们在不同的AppDomain加载,你可以在上面AppDomain.CurrentDomain的地方使用实例。

+0

谢谢你的回答。然而,我的程序集最初不会被加载到应用程序域,我可能需要插入额外的程序集,同时避免重新编译主项目(我在原始问题中没有明确表示道歉)。 – Dangerous 2012-02-03 15:18:40

+0

您可以使用来自您的问题的代码,我的答案中的代码和运行时的'Assembly.Load'的组合来动态地将程序集加载到您的appdomain中。无论如何,只要你加载它们,你的插件只能是可执行的。 – 2012-02-03 15:37:15