向dotnet core 3注册Open Generic [英] Register Open Generic with dotnet core 3
问题描述
我试图在我的应用程序中注册一个Open Generic类型,但是我的行为很奇怪.
I'm trying to register an Open Generic type in my application but I'm having a strange behavior.
以下内容正常运行:
services.AddTransient(typeof(IA<>), typeof(A<>));
现在,我想将参数传递给我的 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");
});
这会产生异常
打开通用服务类型'IA`1 [T]"需要注册一个开放的通用实现类型.(范围'描述符')'
'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.
问题很简单:如何使用默认的.net核心DI注册带有参数的Open Generic?(我不想使用温莎城堡之类的第三方库)
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)
请注意, A<>
的构造函数具有可选参数,这就是为什么 services.AddTransient(typeof(IA<>),typeof(A<>)));的原因.
正在工作
Note that the constructor of A<>
has optional parameter, this is why services.AddTransient(typeof(IA<>), typeof(A<>));
is working
推荐答案
您可以将 A<>
参数的构造函数包装到一个类中,然后将其注入而不是传递参数
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; }
}
这篇关于向dotnet core 3注册Open Generic的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!