簡體   English   中英

如何用Castle Interceptor檢查方法是否具有屬性?

[英]How to check if method has an attribute with Castle Interceptor?

我正在使用Castle Windsor和WCF學習依賴項注入和攔截,並且我想檢查攔截的方法是否具有自定義屬性(LogAttribute)。

(我的示例基於以下答案: https : //stackoverflow.com/a/2593091

服務合同 :

[ServiceContract]
public interface IOrderService
{
    [OperationContract]
    Order GetOrder(int orderId);
}

[DataContract]
public class Order
{
    [DataMember]
    public string Id { get; set; }

    // [...]
}

服務實施:

public class OrderService : IOrderService
{
    private readonly IDatabase _database;

    public OrderService(IDatabase database)
    {
        _database = database;
    }

    [Log] // <- my custom attribute
    public Order GetOrder(int orderId)
    {
        return _database.GetOrder(orderId);
    }
}

public class LogAttribute : Attribute
{ }

簡單數據訪問層:

public interface IDatabase
{
    Order GetOrder(int orderId);
}

public class Database : IDatabase
{
    public Order GetOrder(int orderId)
    {
        return new Order
        {
            Id = orderId
        };
    }
}

依賴注入和攔截:

public class Global : HttpApplication
{
    public static WindsorContainer Container { get; private set; }

    protected void Application_Start(object sender, EventArgs e)
    {
        BuildContainer();
    }

    private static void BuildContainer()
    {
        if (Container != null)
            return;

        Container = new WindsorContainer();

        Container.AddFacility<WcfFacility>();

        Container.Register(Component.For<IInterceptor>().ImplementedBy<MyInterceptor>().LifestyleTransient());
        Container.Register(Component.For<IDatabase>().ImplementedBy<Database>().LifestylePerWcfOperation());
        Container.Register(Component.For<IStringReverser>().ImplementedBy<StringReverser>().Interceptors<MyInterceptor>());
    }
}

public class MyInterceptor : IInterceptor
{
    public void Intercept(IInvocation invocation)
    {
        DoSomeWorkBefore(invocation);

        invocation.Proceed();
    }

    private static void DoSomeWorkBefore(IInvocation invocation)
    {
        if (Attribute.IsDefined(invocation.Method, typeof(LogAttribute)))
        {
            // This part of the code is never executed
            Debug.WriteLine("Method has Log attribute !");
        }
    }
}

我已經嘗試過invocation.Method.GetCustomAttributesAttribute.GetCustomAttribute ,但是找不到LogAttribute。 有任何想法嗎 ?

(Windsor)服務用於IOrderService接口,因此invocation.Method IOrderService將指向接口上沒有屬性的方法。

使用invocation.MethodInvocationTarget來獲取類的方法

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM