用structuremap进行拦截

时间:2010-10-25 08:54:08

标签: structuremap interceptor castle-dynamicproxy

我正在尝试使用结构图进行一些基于属性的拦截,但我正在努力将最后的松散结束起来。

我有一个自定义注册表来扫描我的程序集,在这个注册表中我定义了以下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>());
         ...
    }
}

我正在使用Castle.Core中的DynamicProxy来创建拦截器,但我的问题是从 CreateInterfaceProxyWithTarget(...)调用返回的对象没有实现触发了在structuremap中创建目标实例(即上例中的IOrderProcessor)。我希望IContext参数能够显示这个接口,但我似乎只能掌握具体类型(即上例中的OrderProcessor)。

我正在寻找有关如何使这个场景工作的指导,通过调用ProxyGenerator来返回实现所有接口作为目标实例的实例,方法是从structuremap或通过其他机制获取所请求的接口。

1 个答案:

答案 0 :(得分: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;
    }
}

希望这有助于某人

相关问题