|
Collections
Collection registrations allow multiple implementations of the same service to be grouped together.
IntroductionTo 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. Examplevar 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. |
Sign in to add a comment
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..