(这是一个与
this one相关的问题,适用于SimpleInjector.我建议为每个IoC容器创建单独的问题.)
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中探索类似的方法.从我读取和搜索的内容看起来只有接口/类型级别拦截可用.但我希望能够选择使用这种类型的属性控制拦截行为来装饰各个方法.有什么建议吗?
解决方法
当你说没有方法级拦截时,你是对的.
但是,当您使用write类型拦截器时,您可以访问正在调用的方法.注意:这依赖于Autofac.Extras.DynamicProxy2包.
但是,当您使用write类型拦截器时,您可以访问正在调用的方法.注意:这依赖于Autofac.Extras.DynamicProxy2包.
public sealed class MyCacheAttribute : IInterceptor { public void Intercept(IInvocation invocation) { // grab from cache if I have it,otherwise call the intended method call.. Console.WriteLine("Calling " + invocation.Method.Name); invocation.Proceed(); } }
注册将是这样的.
containerBuilder.RegisterType<PlanRepository>().As<IPlanRepository>().EnableInterfaceInterceptors(); containerbuilder.RegisterType<MyCacheAttribute>();
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。