0

状況:インターフェースとして登録されているクラスがいくつかあります。また、このクラスはカスタム属性でマークされています。App containsewの構築の最後に登録されているすべてのコンポーネントを確認し、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
}

他の属性がたくさんあるかもしれないので、私は花瓶のブートストラップでそれをしたくありません。このアイテム(ツールバー)が最初に要求されたときに、新しいクラスを(1回だけ)追加するのが最善の方法です。

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 に答える