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

自定义类属性:

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


我不想参考,所以我将手动加载程序集。我的目标是基于类属性的标识符解决具体的实现。我已经尝试了很多有关元数据,metadatafrom,键控等的操作。

        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


有人可以帮我弄这个吗?

最佳答案

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

关于attributes - 基于类属性/元数据的Autofac解析,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21828687/

10-11 04:13