无法使用AUTOFAC解析名称valuecollection
-
24-09-2019 - |
题
我正在使用AutoFac 2.1.12来处理我的依赖注入,并且在一个特定问题上遇到麻烦。我似乎无法解析名称valuecollection依赖性。
考虑以下代码段:
class Foo
{
public Foo(NameValueCollection collection) { }
}
static class Run
{
public static void Main()
{
var builder = new ContainerBuilder();
builder.RegisterType<NameValueCollection>();
builder.RegisterType<Foo>();
using (var scope = builder.Build())
scope.Resolve<Foo>();
}
}
它将以无与伦比的依赖关系exception崩溃:
检测到的圆形组件依赖性:foo-> system.collections.specialized.namevaluecollection-> system.collections.collections.specialized.namevaluecollection。
但是,如果我用任何其他类型替换名称valuecollection,则代码正常。
我是在做一些事情,关于我所缺少的名称valuecollection类型是否有一些特别之处,或者这是AutoFac本身的问题?
解决方案
This is by design. See Autowiring:
Autofac automatically chooses the constructor with the most parameters that are able to be obtained from the container.
Try registering NameValueCollection
like so (not sure if this will work, though):
builder.RegisterType<NameValueCollection>().UsingConstructor();
If that doesn't work, try
builder.Register(c => new NameValueCollection());
不隶属于 StackOverflow