借助 Unity,我能够快速添加基于属性的拦截,如下所示
public sealed class MyCacheAttribute : HandlerAttribute, ICallHandler
{
public override ICallHandler CreateHandler(IUnityContainer container)
{
return this;
}
public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
{
// grab from cache if I have it, otherwise call the intended method call..
}
}
然后我用这种方式注册Unity:
container.RegisterType<IPlanRepository, PlanRepository>(
new ContainerControlledLifetimeManager(),
new Interceptor<VirtualMethodInterceptor>(),
new InterceptionBehavior<PolicyInjectionBehavior>());
在我的存储库代码中,我可以有选择地装饰要缓存的某些方法(使用可以为每个方法单独自定义的属性值):
[MyCache( Minutes = 5, CacheType = CacheType.Memory, Order = 100)]
public virtual PlanInfo GetPlan(int id)
{
// call data store to get this plan;
}
我正在探索类似的方法来做到这一点简易注射器。从我阅读和搜索的内容看来,只有接口/类型级别的拦截可用。但我喜欢用这种类型的属性控制拦截行为来装饰各个方法的选项。有什么建议吗?
[编辑:移动Autofac to its 自己的问题 https://stackoverflow.com/questions/28969429/method-level-attributed-interception-with-autofac保持这个问题的焦点]