Home > Back-end >  Handle generic types in GetMethod
Handle generic types in GetMethod

Time:10-22

What would be the correct arguments for GetMethod in the AddService(services, type, instance) exactly defining the generic version (just in case there will come more overloads).

I know I could just keep the method names different but I don't want to.

Currently I get either null or an exception due to multiple found method versions...

The code:

namespace Sample
{

    public interface IService { }

    public static class SampleExtensions
    {

        public static IServiceCollection AddService<T>(this IServiceCollection services, T instance) where T : IService
        {
            //services.AddSingleton<T>(instance);
            services.AddSingleton(instance.GetType(), instance); // register with the concrete implementation type
            //some stuff that only works with generic T
            return services;
        }

        public static IServiceCollection AddService(this IServiceCollection services, Type type, object instance)
        {

            Type classType = typeof(SampleExtensions);
            MethodInfo methodInfo = classType.GetMethod                         // correct arguments??
            (
                nameof(AddService),                                             // only name would bring 2 results
                new Type[] { typeof(IServiceCollection), typeof(object) }       // ??? instance is generic
            );
            MethodInfo genericMethod = methodInfo.MakeGenericMethod(type);
            genericMethod.Invoke(null, new[] { services, instance });           // call the generic method version
            return services;
        }

    }
}

CodePudding user response:

You can use Type.MakeGenericMethodParameter to represent a generic parameter reference:

MethodInfo methodInfo = classType.GetMethod                         
(
    nameof(AddService),                                             
    new Type[] { typeof(IServiceCollection), Type.MakeGenericMethodParameter(0) }      
);
  • Related