I have a generic interface called IConverter which accepts one type of object and returns a different type.
public interface IConverter<TSource, TDestination>
{
Task<TDestination> Convert(TSource source);
}
There are many different implementations of this interface and they are all registered in the DI container (see last post on how to automatically register all implementations of a generic interface in DI container). However, where this converter is used, the source Type and the destination Type are dynamic. This means I cannot dependency inject a specific type of IConverter in the constructor. I could, however, use the IServiceProvider to get the right type of Converter given the source Type and the destination Type.
public class ConverterFactory
{
private readonly IServiceProvider _serviceProvider;
public ConverterFactory(IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
}
public object GetConverter(Type inType, Type outType)
{
var converterType = typeof(IConverter<,>).MakeGenericType(inType, outType);
var converter = _serviceProvider.GetService(converterType);
return converter;
}
}