开发者

Can't resolve NameValueCollection with Autofac

I am using Autofac 2.1.12 to handle my dependency injection, and am having trouble with one specific issue. I can't seem to resolve a NameValueCollection dependency.

Consider the following code snippet:

class Foo
{
    public Foo(NameVal开发者_如何转开发ueCollection 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>();
    }
}

It will crash with an unhandled DependencyResolutionException:

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

However, if I replace NameValueCollection with any other type, the code works fine.

Am I doing something wroing, is there something special about the NameValueCollection type that I am missing, or is this an issue with Autofac itself?


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜