My favorites | Sign in
Logo
                
Search
for
Updated Mar 13, 2009 by nicholas.blumhardt
Collections  
Collection registrations allow multiple implementations of the same service to be grouped together.

Introduction

To register multiple implementations of the same service, use RegisterCollection<T>() - if you want 5 loggers, it is recommended that you create a collection and add the loggers to it. This prevents an ugly situation when all of a sudden you need two distinct collections of loggers in the same application.

Autofac (as of 1.4) now also provides an 'automatic' way to resolve multiple instances of the same service - see ImplicitCollectionSupport.

Example

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

var container = builder.Build();

var loggers = container.Resolve<IEnumerable<ILogger>>();
foreach (var logger in loggers)
  logger.Info("Created my first collection registration!");

Collections are just regular components, so they can be used in autowiring just like anything else.

The IEnumerable<T>, ICollection<T> and IList<T> interfaces are supported.


Comment by carl.hoerberg, May 09, 2009

maybe obvious to most people but any way.. you probably still just want to call logger.Info("info message"); and not put foreach jadajada every where you'd like to make a log message. implement a MultiLogger? which is injeced with the IEnumerable<ILogger> logger and forward the messaged down, but let the MultiLogger? resolve a single ILogger in the rest of the application..

Comment by carl.hoerberg, Jul 15, 2009

also note that builder.RegisterCollection?<ILogger().As<IEnumerable<ILogger>>(); is essentially the same as builder.RegisterCollection?<ILogger>(); as IEnumerable is the default service for RegisterCollection?()..

also the As call in builder.Register<ConsoleLogger>().As<ILogger>().MemberOf?<IEnumerable<ILogger>>(); is unneeded. builder.Register<ConsoleLogger>().MemberOf??<IEnumerable<ILogger>>(); works just as fine.


Sign in to add a comment
Hosted by Google Code