mercredi 10 mars 2021

C# 9 - How to call default interface method with reflection?

I have an interface for automapper. And DTOs implement this interfaces. As you can see there is a default method.

public interface IMap<T> {
    public void Mapping(Profile profile) {
        profile.CreateMap(typeof(T), GetType()).ReverseMap();
    }
}

public class ItemDto : IMap<Item> {
    public string Name { get; set; }
}

When I try to invoke this method. The method cannot be found.

public class MappingProfile : Profile {
    public MappingProfile() {
        ApplyMappingsFromAssembly();
    }

    private void ApplyMappingsFromAssembly() {
        var types = AppDomain.CurrentDomain.GetAssemblies().Where(w => !w.IsDynamic).SelectMany(s => s.GetExportedTypes())
            .Where(t => t.GetInterfaces().Any(i =>
                i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IMap<>)))
            .ToList();

        foreach (var type in types) {
            var instance = Activator.CreateInstance(type);
            var methodInfo = type.GetMethod("Mapping");
            //In here I expect to call default interface method.
            methodInfo?.Invoke(instance, new object[] { this });
        }
    }
}

How can I call default interface method?





Aucun commentaire:

Enregistrer un commentaire