Skip to content

Support OpenGeneric in GetImplementationsForType #1080

@kaylumah

Description

@kaylumah
public static class AssemblyExtensions
{
    public static Type[] GetImplementationsForType(this Assembly assembly, Type interfaceType)
    {
        if (!interfaceType.IsInterface)
        {
            throw new ArgumentException($"The type '{interfaceType.FullName}' is not an interface and cannot be used to scan for implementations!", nameof(interfaceType));
        }

        Type[] assemblyTypes = assembly.GetTypes();

        // Use IsAssignableFrom for non-generic interfaces
        if (!interfaceType.IsGenericTypeDefinition)
        {
            return assemblyTypes
                .Where(type => interfaceType.IsAssignableFrom(type))
                .Where(type => !type.IsInterface && !type.IsAbstract)
                .ToArray();
        }

        // For open generics, use GetInterfaces logic
        return assemblyTypes
            .Where(type =>
                !type.IsInterface &&
                !type.IsAbstract &&
                type.GetInterfaces()
                    .Any(i => i.IsGenericType &&
                              i.GetGenericTypeDefinition() == interfaceType))
            .ToArray();
    }
}```

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions