developer82
developer82

Reputation: 13733

Get classes from assembly that implement a specific interface

I have an interface such as this:

public interface IMyInterface<T>
{
    void MyMethod(T obj);
}

I'm trying to find if an assembly has any classes that implement this. I found some examples but they are all demonstrate checking an implementation of a simple interface that don't have T.

Here is what I wrote:

var interfaceType = typeof(IMyInterface<>);
Assembly assembly = Assembly.LoadFrom(assemblyFile);
var allTypes = assembly.GetTypes();
foreach(Type type in allTypes)
{
     var isImplementing = interfaceType.IsAssignableFrom(type);
}

I also tried doing this:

var interfaces = type.GetInterfaces();
var isImplementing = interfaces.Contains(interfaceType);

isImplementing is always false.

Upvotes: 1

Views: 308

Answers (2)

Robin Gordijn
Robin Gordijn

Reputation: 685

I'm trying to find if an assembly has any classes that implement this.

With your example you need a 'assemblyFile'. Take a look at this example wich I used to get all the classes that implement IMyInterface using CurentDomain (System.AppDomain.CurrentDomain):

public IEnumerable<IMyInterface> GetClasses(AppDomain CurrentDomain)
    {
        var _type = typeof(IMyInterface);

        var _types = CurrentDomain.GetAssemblies().SelectMany(_s => _s.GetTypes()).Where(i => _type.IsAssignableFrom(i) && !i.IsInterface);

        List<IMyInterface> _classes = new List<IMyInterface>();

        foreach (var _instance in _types)
        {
            _classes.Add((IMyInterface)Activator.CreateInstance(_instance));
        }

        return _classes;
    }

*Also note the '!i.IsInterface' using this will not return assemblies which contains the interface

I hope this will help you get some insight fixing your problem.

Upvotes: 0

Rei Mavronicolas
Rei Mavronicolas

Reputation: 1425

You almost had it with the second approach. However the interface types returned by type.GetInterfaces() will be of a specific type implementation e.g. IMyInterface<String>. So you'll have to check your interface type against the GenericTypeDefinition.

Try this:

var interfaces = type.GetInterfaces();
var isImplementing = interfaces.Where(i => i.IsGenericType).Any(i => i.GetGenericTypeDefinition() == interfaceType);

Upvotes: 2

Related Questions