问题
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
回答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; }
}
来源:https://stackoverflow.com/questions/60351317/register-open-generic-with-dotnet-core-3