Search code examples
c#autofac

Resolving multiple keyed services


I'm not sure what I'm missing. I have multiple groups of services that derive from a single interface. Each group needs to be resolved separately:

builder.RegisterType<Bar1>().Keyed<IFoo>("Bars");
builder.RegisterType<Bar2>().Keyed<IFoo>("Bars");
builder.RegisterType<Foo1>().Keyed<IFoo>("Foos");
builder.RegisterType<Foo2>().Keyed<IFoo>("Foos");

What does work:

var keyfoos = scope.ResolveKeyed<IEnumerable<IFoo>>("Foos");
Console.Write("resolved keyfoos: ");
Console.WriteLine(foos == null ? "null" : keyfoos.Count().ToString());

resolved keyfoos: 2

The actual problem is injecting those keyed services:

public class FooBar
{
    public FooBar(
        [KeyFilter("Foos")]
        IEnumerable<IFoo> foos, 
        [KeyFilter("Bars")]
        IEnumerable<IFoo> bars)
    {
        Console.Write("ctor key foos: ");
        Console.WriteLine(foos == null ? "null" : foos.Count().ToString());
        Console.Write("ctor key bars: ");
        Console.WriteLine(bars == null ? "null" : foos.Count().ToString());
    }
}

scope.Resolve<FooBar>();

result:

ctor key foos: 0

ctor key bars: 0

I'd expect both "lists" to have a count of 2 not 0. What am I missing?


Solution

  • Registering the class with the constructor using the KeyFilterAttribute also requires the WithAttributeFiltering()

    Instead of:

    builder.RegisterType<FooBar>().AsSelf();
    

    I needed to

    builder.RegisterType<FooBar>().AsSelf().WithAttributeFiltering();
    

    So now the result is:

    ctor key foos: 2

    ctor key bars: 2