I have a generic interface IApiService responsible for making GET calls to other server. I have three requirements:
- some usages have to be cached
- some usages never should be cached
- some usages don't care about caching and should have default setting that can be easily changed
My idea was to introduce the following hierachy:
public interface IApiService<T> where T : class
{
Task<T> GetAsync(IRequestParameters requestParameters);
}
public interface ICachedApiService<T> : IApiService<T> where T : class
{
}
public interface IDirectApiService<T> : IApiService<T> where T : class
{
}
For case 1 I use ICachedApiService, for case 2 I use IDirectApiService and for case 3 I use IApiService.
I use .NET Core default dependency injection framework. And here's my configuration for ICachedApiService:
serviceCollection.AddScoped(typeof(ICachedApiService<>), typeof(CachedApiService<>);
For IDirectApiService it's different and I have to use lambda method for each generic type
serviceCollection.AddScoped<IDirectApiService<ProductDTO>>(serviceProvider => new
DirectApiService<ProductDTO> (
ProductsEndpoint // and other type specific data
));
The question is how can I configure IApiService to use either IDirectApiService or ICachedApiService? For ICachedApiService it's easy:
serviceCollection.AddScoped(typeof(IApiService<>), typeof(CachedApiService<>));
For IDirectApiService I would prefer not to repeat the configuration for each concrete type as this is error prone and needs more changes if I want to switch to cached version. Is this possible with any dependency injection framework? Is there a way to somehow get the generic parameter that is missing in getService?
serviceCollection.AddScoped(typeof(IApiService<>), x => x.GetService<???>());