0

I'm trying to register an Open Generic type in my application but I'm having a strange behavior.

The following is working correctly:

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

Now, I would like to pass parameters to my A class, because my constructor has some arguments:

services.AddTransient(typeof(IA<>), provider =>
{
    return ActivatorUtilities.CreateInstance(provider, typeof(A<>), "1", "2");
});

This generates an exception

'Open generic service type 'IA`1[T]' requires registering an open generic implementation type. (Parameter 'descriptors')'

Ok so I simplified my factory, and just did something like this:

services.AddTransient(typeof(IA<>), provider => typeof(A<>));

But this generates exactly the same exception.

Question is simple: How to register an Open Generic with parameters with the default .net core DI ? (I don't want to use a third party library like Castle Windsor)

Note that the constructor of A<> has optional parameter, this is why services.AddTransient(typeof(IA<>), typeof(A<>)); is working

Bidou
  • 7,378
  • 9
  • 47
  • 70

1 Answers1

1

You can wrap the constructor of A<> parameters into a class and inject it instead of passing the parameters

services.AddTransient(typeof(IA<>), typeof(A<>));
services.AddTransient<AOptions>(sp => new AOptions { X = "1", Y = "2" });
public class A<T> : IA<T>
{
    private readonly AOptions _aOptions;

    public A(AOptions aOptions = null)
    {
        _aOptions = aOptions;
    }
}

public class AOptions
{
    public string X { get; set; }
    public string Y { get; set; }
}
Piotr L
  • 939
  • 1
  • 6
  • 12
  • That's a good solution but it doesn't explain why the one with the provider is not working? – Bidou Feb 22 '20 at 16:37