如何检查方法是否具有Castle Interceptor的属性?

时间:2014-05-16 18:19:23

标签: c# wcf dependency-injection castle-windsor castle-dynamicproxy

我正在学习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。有什么想法吗?

1 个答案:

答案 0 :(得分:6)

(Windsor)服务用于IOrderService接口,因此invocation.Method将指向接口上的方法,该方法没有该属性。

使用invocation.MethodInvocationTarget获取类的方法