-1

I'm wanting to do a generic scoped. I have a class where it needs to receive a "T" type to instantiate it. My problem is receiving this type "T" otherwise without being explicit.

example:

public class MyClass<T> : IMyInterface<T> where T : class {}

public interface IMyInterface<T> where T : class {}

public void test()
{
   Type xx = new someClass1().GetType();
   Type tt = new someClass2().GetType();
   Type yy = new someClass3().GetType();

   services.AddScoped<IMyInterface<xx>, MyClass<xx>>();
   services.AddScoped<IMyInterface<tt>, MyClass<tt>>();
   services.AddScoped<IMyInterface<yy>, MyClass<yy>>();
}

Another example

public void test()
{
   foreach (Type item in someClass.ToList())
   {
      services.AddScoped<IMyInterface<item>, MyClass<item>>();
   }
}
  • With adittional information: there is overloaded `ServiceCollectionServiceExtensions.AddScoped` which is not generic and take some interesting for you parameters... – Selvin Feb 15 '23 at 00:12
  • I managed to solve the problem with the following code: `var constructed1 = typeof(IMyInterface<>).MakeGenericType(item); var constructed2 = typeof(MyClass<>).MakeGenericType(item); services.AddScoped(constructed1 , constructed2 );` – JONAS MACIEL Feb 15 '23 at 14:05

1 Answers1

-1

This allows the MyMethod method to create an instance of T using the new operator. Note that this approach requires that the type parameter T be constrained in some way in order to be used without being explicitly specified.

public void MyMethod<T>() where T : new()
{
    T instance = new T();
    // code
}
  • This kind of approach is not what I'm looking for, I need to generate a type at compile time and pass that type dynamically into the in MyClass. – JONAS MACIEL Feb 15 '23 at 11:16