2010-10-25 81 views
4

我正在尝试使用结构映射进行一些基于属性的拦截,但我正在努力锁定最后的松散结束。使用结构映射执行拦截

我有一个自定义注册表,它扫描我的程序集,并在此注册表中定义了以下ITypeInterceptor,其目的是匹配使用给定属性修饰的类型,然后在匹配的情况下应用拦截器。该类被定义为这样的:

public class AttributeMatchTypeInterceptor<TAttribute, TInterceptor> 
    : TypeInterceptor 
    where TAttribute : Attribute 
    where TInterceptor : IInterceptor 
{ 
    private readonly ProxyGenerator m_proxyGeneration = new ProxyGenerator(); 

    public object Process(object target, IContext context) 
    { 
     return m_proxyGeneration.CreateInterfaceProxyWithTarget(target, ObjectFactory.GetInstance<TInterceptor>()); 
    } 

    public bool MatchesType(Type type) 
    { 
     return type.GetCustomAttributes(typeof (TAttribute), true).Length > 0; 
    } 
} 

//Usage 
[Transactional] 
public class OrderProcessor : IOrderProcessor{ 
} 
... 
public class MyRegistry : Registry{ 
    public MyRegistry() 
    { 
     RegisterInterceptor(
      new AttributeMatchTypeInterceptor<TransactionalAttribute, TransactionInterceptor>()); 
     ... 
    } 
} 

我使用DynamicProxy从Castle.Core创建拦截器,但我的问题是,对象从CreateInterfaceProxyWithTarget(...)退还调用不实现触发在结构图中创建目标实例的接口(即上例中的IOrderProcessor)。我希望IContext参数能够揭示这个接口,但我似乎只能看到具体类型(例如上例中的OrderProcessor)。

我在寻找关于如何让这个场景工作的指导,要么通过调用ProxyGenerator来返回一个实现所有接口作为目标实例的实例,通过从结构映射或通过其他机制获取请求的接口。

回答

2

我实际上得到了一些小小的警告,所以我只是将其作为答案发布。诀窍是获得接口并将其传递到CreateInterfaceProxyWithTarget。我唯一的问题是,我找不到一种方法来查询目前正在解析哪个接口的IContext,所以我最终只查找了目标上为我工作的第一个接口。见下面

public class AttributeMatchTypeInterceptor<TAttribute, TInterceptor> : 
    TypeInterceptor 
    where TAttribute : Attribute 
    where TInterceptor : IInterceptor 
{ 
    private readonly ProxyGenerator m_proxyGeneration = new ProxyGenerator(); 

    public object Process(object target, IContext context) 
    { 
     //NOTE: can't query IContext for actual interface 
     Type interfaceType = target.GetType().GetInterfaces().First(); 
     return m_proxyGeneration.CreateInterfaceProxyWithTarget(
      interfaceType, 
      target, 
      ObjectFactory.GetInstance<TInterceptor>()); 
    } 

    public bool MatchesType(Type type) 
    { 
     return type.GetCustomAttributes(typeof (TAttribute), true).Length > 0; 
    } 
} 

希望这个代码可以帮助别人