我正在学习 CaSTLe Windsor 和 WCF 的依赖注入(inject)和拦截,我想检查拦截的方法是否具有自定义属性 (LogAttribute)。
(我的示例基于此答案:https://stackoverflow.com/a/2593091)
服务契约(Contract):
[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
};
}
}
依赖注入(inject)和拦截:
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.GetCustomAttributes
和 Attribute.GetCustomAttribute
,但没有找到 LogAttribute。有什么想法吗?
最佳答案
(Windsor) 服务用于 IOrderService
接口(interface),因此 invocation.Method
将指向接口(interface)上的方法,它没有属性。
使用invocation.MethodInvocationTarget
获取类的方法
关于c# - 如何检查方法是否具有 CaSTLe 拦截器的属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23702125/