我有一个可以处理多个规则调用的规则,因此我创建了一个放置在规则类上的自定义属性。此属性列出允许处理的名称。在structuremap中,我想通过读取自定义属性将同一规则注册为多个名称。
[RuleIdentifer(new string[] { "RunAction1","RunAction2","RunAction3" })]
我曾尝试使用MissingNamedInstanceIs类但遇到Bi-Directional依赖性错误。在Scan:
之后,已将以下内容放入容器的创建中_.For<Rules.IRule>().MissingNamedInstanceIs.ConstructedBy("Pull Rule by Name from Attribute",r =>
{
return r.GetAllInstances<Rules.IRule>().FirstOrDefault<Rules.IRule>(r1 =>
{
var dnAttribute = r1.GetType().GetCustomAttributes(typeof(RuleIdentifer), true).FirstOrDefault() as RuleIdentifer;
if (dnAttribute != null && dnAttribute.Names.Contains<string>(r.RequestedName)) return true;
return true;
});
});
在NameBy调用的扫描部分中有更好的方法吗:
x.AddAllTypesOf<Rules.IRule>().NameBy(t => t.Name);
答案 0 :(得分:0)
当提前并创建我自己的RegistrationConvention时。现在按预期工作。
public class RuleAttributeConvention : IRegistrationConvention
{
public void ScanTypes(TypeSet types, Registry registry)
{
// Only work on concrete types
types.FindTypes(TypeClassification.Concretes | TypeClassification.Closed).Where(typ => typeof(Rules.IRule).IsAssignableFrom(typ)).ToList().ForEach(t =>
{
var dnAttribute = t.GetCustomAttributes(typeof(RuleIdentifer), true).FirstOrDefault() as RuleIdentifer;
if (null == dnAttribute) return;
foreach (var nm in dnAttribute.Names)
{
registry.For<Rules.IRule>().Use(t.Name).Name = nm;
}
});
}
}