首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用结构图进行拦截

问用结构图进行拦截
EN

Stack Overflow用户
提问于 2010-10-25 08:54:08
回答 1查看 1.3K关注 0票数 4

我正试图使用结构图进行一些基于属性的拦截,但我很难将最后的松散部分捆绑起来。

我有一个自定义注册表来扫描我的程序集,在这个注册表中,我定义了以下ITypeInterceptor,它的目的是匹配使用给定属性修饰的类型,然后应用拦截器(如果匹配)。该类的定义如下:

代码语言:javascript
复制
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的Castle.Core创建拦截器,但我的问题是从CreateInterfaceProxyWithTarget(.)返回的对象call没有实现触发在结构图中创建目标实例的接口(例如,上面的示例中的IOrderProcessor )。我希望IContext参数能够显示这个接口,但我似乎只能掌握具体的类型(例如,上面的示例中的OrderProcessor )。

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2011-08-09 06:50:28

实际上,我得到了一些有用的东西,但有一点需要注意,所以我会把这个作为答案。诀窍是获得接口并将其传递到CreateInterfaceProxyWithTarget中。我唯一的问题是,我找不到一种方法来查询IContext当前正在解决的接口,所以我最终只查找了对我起作用的目标上的第一个接口。见下面的代码

代码语言:javascript
复制
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;
    }
}

希望这能帮到别人

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4013071

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档