(这是与这一个有关的问题,该问题用于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进行方法级别的属性拦截
发布评论