2

I have an extension method that registers some services :

endpoints.MapService<MyService>();

Behind the scenes the extension method looks like:

public static void MapService<TService>(this IEndpointRouteBuilder builder) where TService : class

Now I don't have the actual classes to configure at runtime but I do have the Type of the class which is typeof(MyService), how can I use that to register my service using the extension method MapService? I am guessing some methods in the reflection namespace could help me with that.

Sameed
  • 655
  • 1
  • 5
  • 18
  • 2
    Does this answer your question? [How to call generic method if I have only Type instance?](https://stackoverflow.com/questions/6805814/how-to-call-generic-method-if-i-have-only-type-instance) – vernou Jun 22 '21 at 13:39
  • 1
    What does the method actually do? Some IoC frameworks have overloads that take type-objects as parameters, with a generic overload for convenience. – JonasH Jun 22 '21 at 13:39
  • I really don't understand what you are trying to achieve, I think that you want to do something like swagger??? – Iria Jun 22 '21 at 13:45

1 Answers1

2

You will need to retrieve the generic definition of the MapService function and then make a generic method out of it using MethodInfo.MakeGenericMethod(), like so:

// This needs to be the type which contains "MapService".
Type typeWhereMapServiceIs = typeof(ServiceExtensionMethods);

MethodInfo mapServiceMethod = typeWhereMapServiceIs.GetMethod("MapService", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static);

MethodInfo mapServiceMyService = mapServiceMethod.MakeGenericMethod(typeof(MyService));

mapServiceMyService.Invoke(null, new object[] { builder });
Space
  • 175
  • 9