使用Autofac进行方法级别的属性拦截

编程入门 行业动态 更新时间:2024-10-27 16:27:55
本文介绍了使用Autofac进行方法级别的属性拦截的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

(这是与这一个有关的问题,该问题用于SimpleInjector建议我为每个IoC容器分别创建问题.)

(this is a related question to this one which is for SimpleInjector. I was recommended to create separate questions for each IoC container.)

使用Unity,我可以像这样快速添加基于属性的拦截

With Unity, I'm able to quickly add an attribute based interception like this

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注册:

Then I register with Unity this way:

container.RegisterType<IPlanRepository, PlanRepository>(new ContainerControlledLifetimeManager(), new Interceptor<VirtualMethodInterceptor>(), new InterceptionBehavior<PolicyInjectionBehavior>());

在我的存储库代码中,我可以选择性地装饰某些要缓存的方法(具有可以为每个方法分别定制的属性值):

In my repository code, I can selectively decorate certain methods to be cached (with attribute values that can be customized individually for each method) :

[MyCache( Minutes = 5, CacheType = CacheType.Memory, Order = 100)] public virtual PlanInfo GetPlan(int id) { // call data store to get this plan; }

我正在用 Autofac 探索类似的方法.从我阅读和搜索的内容来看,似乎只有接口/类型级别的拦截可用.但是我很乐意用这种类型的属性控制的拦截行为来装饰单个方法.有什么建议吗?

I'm exploring similar ways to do this in Autofac. From what I read and searched looks like only interface/type level interception is available. But I would love the option of decorating individual methods with this type of attribute controlled interception behavior. Any advise?

推荐答案

当您说没有方法级别的拦截时,您是对的. 但是,当您使用编写类型拦截器时,您可以访问被调用的方法. 注意:这依赖于Autofac.Extras.DynamicProxy2程序包.

You're right when you say there's no method level interception. However, when you use write a type interceptor you have access to the method that is being invoked. Note: this relies on the Autofac.Extras.DynamicProxy2 package.

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>();

更多推荐

使用Autofac进行方法级别的属性拦截

本文发布于:2023-11-05 21:14:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1561876.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:属性   级别   方法   Autofac

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!