c# – 使用Simple Injector进行方法级别的属性拦截
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了c# – 使用Simple Injector进行方法级别的属性拦截,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2276字,纯文字阅读大概需要4分钟。
内容图文
![c# – 使用Simple Injector进行方法级别的属性拦截](/upload/InfoBanner/zyjiaocheng/809/ec6d2fce07af485f90d19f40dfea359c.jpg)
使用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;
}
我在Simple Injector中探索类似的方法.从我读取和搜索的内容看起来只有接口/类型级别拦截可用.但我希望能够选择使用这种类型的属性控制拦截行为来装饰各个方法.有什么建议吗?
[编辑:将Autofac移至own question以保持此问题的重点]
解决方法:
Simple Injector缺乏用于动态拦截的开箱即用功能,因为这不符合其设计原则,如here所述.但是可以添加拦截功能,例如使用Castle DynamicProxy,如here所示.它也应该是可以在Simple Injector之上使用Unity的拦截功能,但我从未尝试过.
但是,在使用DynamicProxy时,必须将拦截器类与属性类分开.这实际上是一种更好的做法,因为这样可以保留属性passive,并防止强制您的代码库依赖拦截库.
使用DynamicProxy实现此功能时,它可能如下所示:
public class MyCacheInterceptor : IInterceptor
{
public void Intercept(IInvocation invocation) {
var method = invocation.GetImplementationMethod();
var attribute = method.GetCustomAttribute<MyCacheAttribute>();
if (attribute == null) {
// Calls the decorated instance.
invocation.Proceed();
} else {
// caching here
}
}
}
public static class InvocationExtensions
{
public static MethodInfo GetImplementationMethod(this IInvocation invocation) {
// NOTE: bit naive implementation
var method = invocation.GetConcreteMethod();
return invocation.InvocationTarget.GetType().GetMethod(method.Name);
}
}
然而,Simple Injector通过应用SOLID原则和使用装饰器来促进面向方面编程.在我编写的应用程序中,我定义了一般的抽象,例如IRepository< TEntity>和IQueryHandler< TQuery,TResult>这使得通过装饰器应用缓存变得微不足道.装饰器的好处在于它们更清洁(因为它们根本不依赖于任何框架)并且性能更高.
内容总结
以上是互联网集市为您收集整理的c# – 使用Simple Injector进行方法级别的属性拦截全部内容,希望文章能够帮你解决c# – 使用Simple Injector进行方法级别的属性拦截所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。