不能使用Autofac解析NameValueCollection

我正在使用Autofac 2.1.12来处理依赖项注入,并且遇到一个特定问题.我似乎无法解决NameValueCollection依赖项.

考虑以下代码片段:

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>();
    }
}

它将因未处理的DependencyResolutionException崩溃:

Circular component dependency
detected: Foo ->
System.Collections.Specialized.NameValueCollection
-> System.Collections.Specialized.NameValueCollection.

但是,如果我将NameValueCollection替换为任何其他类型,则代码可以正常工作.

我是否在做某些事情,是否缺少我所缺少的NameValueCollection类型,或者这是Autofac本身的问题?

解决方法:

这是设计使然.查看Autowiring

Autofac automatically chooses the constructor with the most parameters that are able to be obtained from the container.

尝试像这样注册NameValueCollection(尽管不确定是否可以工作):

builder.RegisterType<NameValueCollection>().UsingConstructor();

如果这不起作用,请尝试

builder.Register(c => new NameValueCollection());
上一篇:NET Core 3.0 AutoFac替换内置DI的新姿势


下一篇:.net core 注入机制与Autofac