Autofac基于类属性/元数据解析

时间:2014-02-17 12:06:59

标签: attributes autofac

我想根据类属性注册并解析动态加载的类型。我的代码如下:

自定义类属性:

[MetadataAttribute]
public class FooIdentifier : Attribute
{
    public string Identifier { get; private set; }

    public FooIdentifier(string identifier)
    {
        this.Identifier = identifier;
    }
}

我的抽象基类

public abstract class Base
{
    public abstract bool Execute(object param);

    public bool Run(object param = null)
    {
        //...
        return true;
    }
}

我的实施类型

[FooIdentifier("230")]
public class Child1 : Base
{
    public override bool Execute(object param)
    {
        throw new NotImplementedException();
    }
}

[FooIdentifier("250")]
public class Child2 : Base
{
    public override bool Execute(object param)
    {
        throw new NotImplementedException();
    }
}

我不想有硬参考,所以我会手动加载程序集。我的目标是基于class属性的Identifier来解决具体实现。我已经尝试了很多元数据,元数据,键控等等。我目前的尝试是:

        var builder = new ContainerBuilder();
        var assembly = Assembly.LoadFrom(@"[PathToAssembly].dll");

        builder.RegisterModule<AttributedMetadataModule>();

        builder.RegisterAssemblyTypes(assembly)
            .Where(t => t.IsSubclassOf(typeof(Base)))
            //.As<Base>() or .AsImplementedInterfaces()
            .WithMetadataFrom<TaskIdentifier>();

        var container = builder.Build();
        var child = test.ResolveKeyed<Base>("230"); // here i want to have child1

有人可以帮我这个吗?

1 个答案:

答案 0 :(得分:6)

 builder.RegisterAssemblyTypes(assembly)
        .Where(t => t.IsSubclassOf(typeof(Base)) &&
                    t.GetCustomAttribute<FooIdentifier>() != null)
        .Keyed<Base>(t => t.GetCustomAttribute<FooIdentifier>().Identifier);