Ninject:按属性截取,而不从InterceptAttribute派生
本文关键字:InterceptAttribute 派生 属性 截取 Ninject | 更新日期: 2023-09-27 18:25:01
我正在寻找一种方法,使用Ninject将拦截器连接到基于某个属性的方法调用。Ninject提供了InterceptAttribute
基类来实现这一点,这很巧妙,但我希望通过自定义属性来实现这。原因是我想用与业务相关的属性来装饰某些域服务接口,所以我不能让任何东西与其中的框架紧密耦合
这可能吗?
您可以从InterceptorRegistrationStrategy
派生并重写Execute(IPlan plan)
方法(可能还有RegisterClassInterceptors
)以使用您自己的属性类型,而不是ninject的InterceptAttribute
。
然后,您需要将实现注册为内核组件:
this.Kernel.Components.Add<IPlanningStrategy, MyInterceptorRegistrationStrategy>();
您可能还必须了解InterceptorRegistrationStrategy
、AutoNotifyInterceptorRegistrationStrategy
和MethodInterceptorRegistrationStrategy
是如何工作的,这样您才能创建一个有效且无副作用的实现。(这并不取代拦截扩展,而只是扩展了它)。
还有一个stackoverflow的答案,涵盖了一个可能有用的自定义策略:Ninject拦截任何具有特定属性的方法?
当然,你也可以使用其他方法进行拦截:
- 通过绑定,为整个类型(如
Bind<IFoo>().To<Foo>().Intercept().With<MyInterceptor>()
)定义拦截,并让MyInterceptor
检查是否应该拦截给定的方法 - 使用约定API或自己编写类似内容,搜索所有自定义拦截属性,然后使用以下语法:
Kernel.InterceptAround<CustomerService>(
s=>s.GetAllCustomers(),
invocation =>logger.Info("Retrieving all customers..."),
invocation =>logger.Debug("Customers retrieved"));
(另请参阅ninject拦截)