1

I have a method to get all interface implementations from Assembly:

public static class AssemblyExtensions
{
    /// <summary>
    /// Gets all implementations of interface or class from assembly
    /// </summary>
    /// <param name="assembly"></param>
    /// <param name="ofType">Interface or class type</param>
    /// <returns></returns>
    /// <exception cref="Exception"></exception>
    public static IEnumerable<Implementation> GetAllImplementations(this Assembly assembly, Type ofType)
    {
        var types = assembly.GetTypes()
            .Where(type => !type.IsAbstract && !type.IsGenericTypeDefinition);

        var implementations = new List<Implementation>();

        foreach (var type in types)
        {
            if (ofType.IsInterface)
            {
                var typeInterfaces = type.GetInterfaces();
                Type? matchingInterface = null;

                if (ofType.IsGenericType)
                {
                    matchingInterface = typeInterfaces
                        .FirstOrDefault(i => i.IsGenericType && i.GetGenericTypeDefinition() == ofType);

                }
                else
                {
                    matchingInterface = typeInterfaces
                        .FirstOrDefault(i => !i.IsGenericType && i == ofType);
                }

                if (matchingInterface != null)
                {
                    implementations.Add(
                        new Implementation(matchingInterface, type)
                    );
                }
            }
            else if (ofType.IsClass)
            {
                if (
                    ofType.IsGenericType &&
                    type.BaseType?.IsGenericType == true &&
                    type.BaseType?.GetGenericTypeDefinition() == ofType
                )
                {
                    implementations.Add(
                        new Implementation(type.BaseType, type)
                    );
                }
                else if (type.BaseType == ofType)
                {
                    implementations.Add(
                        new Implementation(type.BaseType, type)
                    );
                }
            }
            else
            {
                throw new Exception("ofType can only be interface or class");
            }
        }

        return implementations;
    }

     public record Implementation(Type BaseType, Type ImplementationType);
}

And I can use it like this:

assembly.GetAllImplementations(typeof(MyInterface<,>));

I need get something similar but from IAssemblySymbol - for example for each implementation of MyInterface<T,K> I want to know "T", "K" and their namespaces, and name and namespace of the type that implements MyInterface<T,K>. How I can do that?

user606521
  • 14,486
  • 30
  • 113
  • 204

0 Answers0