gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 16:27:40 24 4
gpt4 key购买 nike

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

自定义类属性:

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

我不想有一个硬引用,所以我将手动加载程序集。我的目标是根据类属性的Identifier解析具体实现。我已经尝试了很多元数据、metadatafrom、keyed 等。我目前的尝试是:

        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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com