views:

99

answers:

1

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

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?

+2  A: 

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());
Anton Gogolev
Add some parentheses to that `new NameValueCollection()` and all will be swell :)
Peter Lillevold