'How to add Dependency Injection to IServiceCollection for nested generic constraint?
here is the ERROR code
var services = new ServiceCollection();
// A<> is not right here
services.AddSingleton(typeof(I<>), typeof(A<>));
var sp = services.BuildServiceProvider();
sp.GetRequiredService<I<W<int>>>();
public interface I<T> { }
public class W<T> { }
public class A<T> : I<W<T>> { }
I have some A<T> implemented I<W<T>>, but if I use the above approach it will try to initialize A<W<T>> for I<W<T>> but what I actually want is A<T>
Update 1: If use
var interfaceType = typeof(I<>).MakeGenericType(typeof(W<>));
services.AddSingleton(interfaceType, typeof(A<>));
An exception is thrown when building the service provider
- $exception {"Cannot instantiate implementation type 'A`1[T]' for service type 'I`1[W`1[T]]'."} System.ArgumentException
Solution 1:[1]
This should be something like
services.AddSingleton(typeof(I<W<>>), typeof(A<>));,
but that would not even compile. I think sou you need to put some variables in place
var interfaceType = typeof(I<>).MakeGenericType(typeof(W<>));
services.AddSingleton(interfaceType , typeof(A<>));
Solution 2:[2]
Itried with the codes and seems succeeded:
public class W<T> { }
public interface I<T>{ }
public class A<T>: I<T> where T : W<T> { }
In startup:
services.AddTransient(typeof(I<>), typeof(A<>));
The Result:
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Cristian-?tef?ni?? Sc?ueru |
| Solution 2 |

