2010-10-25 79 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; 
    } 
} 

希望這個代碼可以幫助別人