我正试图使用结构图进行一些基于属性的拦截,但我很难将最后的松散部分捆绑起来。
我有一个自定义注册表来扫描我的程序集,在这个注册表中,我定义了以下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的Castle.Core创建拦截器,但我的问题是从CreateInterfaceProxyWithTarget(.)返回的对象call没有实现触发在结构图中创建目标实例的接口(例如,上面的示例中的IOrderProcessor )。我希望IContext参数能够显示这个接口,但我似乎只能掌握具体的类型(例如,上面的示例中的OrderProcessor )。
我正在寻找关于如何让这个场景工作的指导,方法是调用ProxyGenerator返回一个实现所有接口作为目标实例的实例,通过从结构图获取请求的接口,或者通过其他机制。
发布于 2011-08-09 06:50:28
实际上,我得到了一些有用的东西,但有一点需要注意,所以我会把这个作为答案。诀窍是获得接口并将其传递到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;
}
}希望这能帮到别人
https://stackoverflow.com/questions/4013071
复制相似问题