Autofac: Allow Type Instances

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 allow all instances of type I as IEnumerable (Array or Collection it does not matter).

In Windsor, I would write the following.

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

I am migrating from Windsor to Autofac 1.4.4.561, but cannot see the equivalent syntax.

+48
c # autofac
Sep 10 '09 at 15:57
source share
2 answers

For current versions of Autofac: (2.0+, so all you have to use today)

You register several ILoggers (for example):

 var builder = new ContainerBuilder(); builder.Register<ConsoleLogger>() .As<ILogger>(); builder.Register<EmailLogger>() .As<ILogger>() .PreserveExistingDefaults(); //keeps console logger as the default 

Then we get all ILogger s:

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

You do not need to do anything, just ask the IEnumerable<T> type you want. Autofac has collector support out of the box, as well as other adapters that can complement your components with additional features.

This is the same use as the pre-2.x ImplicitCollectionSupportModule, but baked directly.

For older versions (0.X - 1.4)

Two ways:

1) Use 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 IEnumerable.

or 2) You can use the ImplicitCollectionSupport module, which will make the code work like newer versions of Autofac:

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

Then enable the ILogger collection instead of finding a solution.

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

which again gives you IEnumerable.

+66
Sep 10 '09 at 16:03
source share

Update for the new version (2.x). Now you only need:

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

RegisterCollection() or ImplicitCollectionSupportModule is no longer needed - this function is out of the box.

+54
Aug 26 '10 at 11:55
source share



All Articles