views:

220

answers:

2

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,

+5  A: 

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

Update: 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.

Peter Lillevold
A: 

Peter, what he means is default convention scanning that is available in StructureMap. It automatically binds IX and X where X is a class that implements interface IX. It works like this:

    public override void Process(Type type, Registry registry)
    {
        if (!type.IsConcrete()) return;

        Type pluginType = FindPluginType(type);
        if (pluginType != null && Constructor.HasConstructors(type))
        {
            registry.AddType(pluginType, type);
            ConfigureFamily(registry.For(pluginType));
        }
    }

    public virtual Type FindPluginType(Type concreteType)
    {
        string interfaceName = "I" + concreteType.Name;
        Type[] interfaces = concreteType.GetInterfaces();
        return Array.Find(interfaces, t => t.Name == interfaceName);
    }

I would also like to know if Autofac supports a similar thing. StructureMap lets you define your own IRegistrationConvention's. This is one example of a convention.

The new assembly scanning feature (http://code.google.com/p/autofac/wiki/Scanning) in Autofac2 probably covers a lot of ground here. See my updated answer.
Peter Lillevold
Thanks for your answer :) will look into it.