I would like to retrieve an enumeration of instantiated classes that implement an interface from across several assemblies within a solution folder.
I have a the following folder structure (if this makes sense):
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
Therefore, if the interface being implemented is ISettings, then I would like an IEnumerable<ISettings> referencing instantiated objects of that interface.
So far, I have used reflection to retrieve the classes that implement the interface from a known class name:
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();
but this is a single assembly and I will not actually know the class names.
Can this be achieved using reflection or does it require something more?
To resolve this issue, I set the post build event of the each project in the solution folder to copy its assembly to the bin folder in the main projects bin folder.
The post build event was set similar to:
Then I used the following to retrieve the assembly file names from this bin directory (credit to Darin for his solution post here):
Then I retrieved implementations of the objects implementing the interface ISettings using:
This allows me to add further projects that implement settings without recompiling the main project.
Additionally, one alternative I looked at was to use
MEFwhere an introduction can be found here.