Discover all non-abstract types implementing an interface in C#

It’s sometimes useful to auto-discover types in C# and other high-level programming languages, even outside the context of coding an IoC container. In C#, robust type-discovery mechanisms make this easy. Here’s a basic formula for auto-discovery of types implementing an interface:

1. Get the list of assemblies in the application domain.
2. Get the types from each discovered assembly.
3. Test each type to see whether it implements the target interface.

This basic formula can be accomplished in a snap using Linq:

var targetType = typeof(someInterface);
var types =
    .SelectMany(a => a.GetTypes())
    .Where(t => t.GetInterfaces().Contains(targetType) && t.IsClass && !t.IsAbstract)
    .OrderBy(t => t.FullName);

Note that t.IsClass (or !t.IsInterface) in the above expression excludes the interface itself, as well as derived interfaces. The .IsAbstract check can be skipped if the goal is to discover all class types for the interface, not just those that can actually be instantiated. Lastly, the basic approach is similar but the calls not identical for .NET Core.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s