(这是一个与 this one相关的问题,适用于SimpleInjector.我建议为每个IoC容器创建单独的问题.) 使用Unity,我可以快速添加基于属性的拦截 public sealed class MyCacheAttribute : HandlerAttribute, ICallHandler
使用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中探索类似的方法.从我读取和搜索的内容看起来只有接口/类型级别拦截可用.但我希望能够选择使用这种类型的属性控制拦截行为来装饰各个方法.有什么建议吗?
当你说没有方法级拦截时,你是对的.但是,当您使用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>();