Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AutoFac Autowiring Conventions

StructureMap has the ability to apply conventions when scanning. Thus IFoo => Foo, without explicit registration.

Is something simular available in AutoFac? Looked around and just can't find anything helpfull.

Thanks,

like image 621
Johannes Avatar asked Oct 26 '09 17:10

Johannes


1 Answers

For Autofac versions from v2

The new scanning features in Autofac2 will imo remove some of the need for registration-by-convention. Lets say that Foo lives in Plugins.dll:

var assembly = Assembly.Load("Plugins");
builder.RegisterAssemblyTypes(assembly)
       .AsImplementedInterfaces();

This registration will pick up Foo and register it as IFoo.

For Autofac versions less than v2

You can use the ContainerBuilder.RegisterTypesMatching. Here's an example:

var builder = new ContainerBuilder();
builder.RegisterTypesMatching(type => type.IsAssignableFrom(typeof(IFoo)));
var container = builder.Build();

var foo = container.Resolve<Foo>();
like image 111
Peter Lillevold Avatar answered Nov 13 '22 07:11

Peter Lillevold