【发布时间】:2015-03-10 16:45:57
【问题描述】:
(这是一个与 this one 相关的问题,它是针对 SimpleInjector 的。建议我为每个 IoC 容器创建单独的问题。)
使用 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 中探索类似的方法。从我阅读和搜索的内容来看,似乎只有接口/类型级别的拦截可用。但我喜欢用这种属性控制的拦截行为来装饰单个方法的选项。有什么建议吗?
【问题讨论】:
标签: dependency-injection autofac ioc-container