tags:

views:

431

answers:

2

Given the following registrations

builder.Register<A>().As<I>();
builder.Register<B>().As<I>();
builder.Register<C>().As<I>();

var container = builder.Build();

I am looking to resolve all instances of type I as a IEnumerable (Array or Collection it doesnt matter).

In Windsor I would have written the following.

foreach(I i in container.ResolveAll<I>())
{
 ...
}

I am migrating from Windsor to Autofac 1.4.4.561 but can't see the equivalent syntax.

Thanks.

+6  A: 

Warning: may be from pre 1.4, but should still be the right direction...

Two ways:

1) Use the collection registration

var builder = new ContainerBuilder();
builder.RegisterCollection<ILogger>()
  .As<IEnumerable<ILogger>>();

builder.Register<ConsoleLogger>()
  .As<ILogger>()
  .MemberOf<IEnumerable<ILogger>>();

builder.Register<EmailLogger>()
  .As<ILogger>()
  .MemberOf<IEnumerable<ILogger>>();

Then:

var loggers = container.Resolve<IEnumerable<ILogger>>();

which gives you an IEnumerable.

or 2) You can use the ImplicitCollectionSupport module, which will make your code above work as listed - just add the registerModule call...

builder.RegisterModule(new ImplicitCollectionSupportModule());
builder.Register(component1).As<ILogger>;
builder.Register(component2).As<ILogger>;

Then resolve a collection of ILogger rather than looking for resolving all.

var loggers = container.Resolve<IEnumerable<ILogger>>();

which gives you an IEnumerable, again.

Philip Rieck
Perfect. Went for option one as its seems more efficient because the container "knows" what to put in the collection. Second option iterates though every registration in the container hierarchy looking for matching types.
crowleym
+1  A: 

An update for the sake of the new (2.x) version. All you need now is:

container.Resolve<IEnumerable<I>>();

There's no longer a need for RegisterCollection() or ImplicitCollectionSupportModule - this functionality comes out of the box.

Nicholas Blumhardt