我正在嘗試使用結構映射進行一些基於屬性的攔截,但我正在努力鎖定最後的鬆散結束。使用結構映射執行攔截
我有一個自定義註冊表,它掃描我的程序集,並在此註冊表中定義了以下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來返回一個實現所有接口作爲目標實例的實例,通過從結構映射或通過其他機制獲取請求的接口。