In the last post, I showed how to dynamically get an instance of the generic type from DI container. In this post, I’m going to show how to call a generic method from that instance of the generic type dynamically using Reflection.
From the last post, this is what the generic interface looks like
public interface IConverter<TSource, TDestination>
{
Task<TDestination> Convert(TSource source);
}
I’m going to add a new method in the the factory from last post to not just getting an instance of the converter based on the source Type and destination Type but also callling the Convert method on the instance.
public class ConverterFactory
{
private readonly IServiceProvider _serviceProvider;
public ConverterFactory(IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
}
public async Task<object> Convert(Type inType, Type outType, object inObject)
{
var converterType = typeof(IConverter<,>).MakeGenericType(inType, outType);
var converter = _serviceProvider.GetService(converterType);
var task = (Task)converterType.InvokeMember("Convert", BindingFlags.InvokeMethod, null, converter, new object[] { inObject });
await task;
var resultProperty = task.GetType().GetProperty("Result");
var result = resultProperty.GetValue(task);
return result;
}
}