So you could loop through every type and figure out if that type has a method called Start
with the exact signature you need. Perhaps better would be to create an interface and make all your classes implement that. For example:
public interface IStartable
{
void Start();
}
public class SomeClass : IStartable
{
public void Start()
{
Console.WriteLine("Starting inside SomeClass");
}
}
Now you can loop through all loaded assemblies and search for implementations of IStartable
, for example:
var instances = AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(a => a.GetTypes())
.Where(t => t.IsClass && typeof(IStartable).IsAssignableFrom(t))
.Select(t => (IStartable)Activator.CreateInstance(t));
foreach (var instance in instances)
{
instance.Start();
}
This is assuming all those classes have a public, parameterless constructor.
This will work but isn't particularly efficient. If you wanted to scale this up a bit, then you might want to look at other options such as Managed Extensibility Framework.
To make this more generic and useful in more situations, here it is wrapped in a method you can apply to any type:
public void RunOnAll<T>(Action<T> action)
{
var instances = AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(a => a.GetTypes())
.Where(t => t.IsClass && typeof(T).IsAssignableFrom(t))
.Select(t => (T)Activator.CreateInstance(t));
foreach (var instance in instances)
{
action(instance);
}
}
So now you would call it like this:
RunOnAll<IStartable>(x => x.Start());