如何检查方法是否有城堡拦截器的属性

本文关键字:城堡 属性 是否 何检查 检查 方法 | 更新日期: 2023-09-27 18:03:48

我正在学习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将指向接口上没有该属性的方法。

使用invocation.MethodInvocationTarget获取类的方法