Home > Enterprise >  How to add Dependency Injection to IServiceCollection for nested generic constraint?
How to add Dependency Injection to IServiceCollection for nested generic constraint?

Time:04-16

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

CodePudding user response:

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<>));

CodePudding user response:

Itried with the codes and seems succeeded:

public class W<T> { }

public interface I<T>where T: W<T> { }
    
public class A<T>: I<T> where T : W<T> { }

In startup:

services.AddTransient(typeof(I<>), typeof(A<>));

The Result:

enter image description here

  • Related