How do you use reflection to discover all types in an assembly that implement a specific interface, useful for plugin discovery?
Short answer
Assembly.GetTypes() returns every type defined in an assembly; filter that collection using LINQ combined with Type.IsAssignableFrom() (or the interface Type's .IsAssignableFrom on each candidate) to find only the concrete, non-abstract classes that implement your target…
Advertisement
AModel answer
Assembly.GetTypes() returns every type defined in an assembly; filter that collection using LINQ combined with Type.IsAssignableFrom() (or the interface Type's .IsAssignableFrom on each candidate) to find only the concrete, non-abstract classes that implement your target interface.
var pluginTypes = Assembly.GetExecutingAssembly()
.GetTypes()
.Where(t => typeof(IPlugin).IsAssignableFrom(t) && !t.IsInterface && !t.IsAbstract);
foreach (var type in pluginTypes) {
var plugin = (IPlugin)Activator.CreateInstance(type)!;
plugin.Execute();
}Real-world example
Building an extensible plugin system that automatically discovers and loads every IPlugin implementation in a loaded assembly.
Likely follow-ups
- How would you extend this to scan MULTIPLE assemblies loaded from a plugins directory at runtime?
Related topics