【问题标题】:How to check if method has an attribute with Castle Interceptor?如何检查方法是否具有 Castle Interceptor 的属性?
【发布时间】:2014-07-05 07:27:25
【问题描述】:

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

【问题讨论】:

  • 你能更好地定义“它不起作用”吗?为什么它不起作用?
  • @Steve :“它不起作用”意味着“if”之后的代码永远不会执行,尽管该方法具有“LogAttribute”。感谢您的评论,我编辑了问题(我是法国人)

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


【解决方案1】:

(Windsor) 服务是针对IOrderService 接口的,所以invocation.Method 将指向接口上的方法,该方法没有属性。

使用invocation.MethodInvocationTarget获取类的方法

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多