开发者

AutoFac Autowiring Conventions

StructureMap has the ability to apply conventi开发者_StackOverflowons when scanning. Thus IFoo => Foo, without explicit registration.

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

Thanks,


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜