Context: .NET 3.5, VS2008. I'm not sure about the title of this question, so feel free to comment about the title, too :-)
Here's the scenario: I have several classes, say Foo and Bar, all of them implement the following interface:
public interface IStartable
{
void Start();
void Stop();
}
And now I'd like to have a container class, which gets an IEnumerable<IStartable> as an argument in its constructor. This class, in turn, should also implement the IStartable interface:
public class StartableGroup : IStartable // this is the container class
{
private readonly IEnumerable<IStartable> startables;
public StartableGroup(IEnumerable<IStartable> startables)
{
this.startables = startables;
}
public void Start()
{
foreach (var startable in startables)
{
startable.Start();
}
}
public void Stop()
{
foreach (var startable in startables)
{
startable.Stop();
}
}
}
So my question is: how can I do it without manually writing the code, and without code generation? In other words, I'd like to have somethig like the following.
var arr = new IStartable[] { new Foo(), new Bar("wow") };
var mygroup = GroupGenerator<IStartable>.Create(arr);
mygroup.Start(); // --> calls Foo's Start and Bar's Start
Constraints:
- No code generation (that is, no real textual code at compile time)
- The interface has only void methods, with or without arguments
Motivation:
- I have a pretty large application, with a lot of plugins of various interfaces. Manually writing a "group container" class for each interface "overloads" the project with classes
- Manually writing the code is error prone
- Any additions or signature updates to the IStartable interface will lead to (manual) changes in the "group container" class
- Learning
I understand that I have to use reflection here, but I'd rather use a robust framework (like Castle's DynamicProxy or RunSharp) to do the wiring for me.
Any thoughts?