0

情况:我们有几个类,注册为接口。这些类也标有自定义属性。我们希望在 App 容器构建结束时遍历所有已注册的组件,并基于 ot 创建新的注册。例如,

[CustomAttribute]
public class Foo: IFoo
{
    [NewCustomActionAttribute("Show me your power!")]
    public void Do() {}
}

所以我们正在这样做 -builder.Register<Foo>.As<IFoo>();
并且将很多类似的类放入另一个插件中。注册完所有插件后,我们想向构建器添加新类,例如带有标题和模块等元数据的 ICustomAction,然后根据此注册加载它。最好的方法是什么?

更新:

var types = // get all registered types
foreach (var typeToProceed in types.Where(_ => _.GetCustomAttributes(typeof(CustomAttribute), false).FirstOrDefault != null)
{
   var customMethodAttributes = // Get NewCustomActionAttributes from this type
   for each customAttr
       builder.Register(new CustomClass(customAttr.Caption, dynamic delegate to associated method);
   end for aech
}

我不想在花瓶引导程序中这样做,因为可能还有很多其他属性。最好的方法是在首先请求此项目(工具栏)时添加(仅一次)新类。

4

1 回答 1

1

我将创建一个新的扩展方法RegisterCustomClasses来处理注册:

public static class AutofacExtensions
{
    public void RegisterCustomClasses<T>(this ContainerBuilder builder)
    {
        var methods = typeof(T).GetMethods();
        var attributes = methods.Select(x => new
                                        {
                                            Method = x,
                                            Attribute = GetAttribute(x)
                                        })
                                .Where(x => x.Attribute != null);

        foreach(var data in attributeData)
            builder.RegisterInstance(new CustomClass(data.Attribute.Caption, 
                                                     data.Method));
    }

    private static NewCustomActionAttribute GetAttribute(MethodInfo method)
    {
        return method.GetCustomAttributes(typeof(NewCustomActionAttribute))
                     .OfType<NewCustomActionAttribute>()
                     .FirstOrDefault()
    }
}

用法:

builder.Register<Foo>.As<IFoo>();
builder.RegisterCustomClasses<Foo>();
于 2012-11-28T14:08:17.363 回答