我正在寻找一种方法,使用 Ninject 将拦截器连接到基于特定属性的方法调用。 Ninject 提供了 InterceptAttribute 基类来执行此操作,这很简洁,但是我想使用自定义属性来实现此目的。原因是我想用业务相关的属性来装饰某些领域服务接口(interface),所以我不能让任何东西与框架紧密耦合。
这可能吗?
最佳答案
您可以从 InterceptorRegistrationStrategy
派生并覆盖 Execute(IPlan plan)
方法(可能还有 RegisterClassInterceptors
)来使用您自己的属性类型而不是 ninject 的 InterceptAttribute
.
然后您需要将实现注册为内核组件:
this.Kernel.Components.Add<IPlanningStrategy, MyInterceptorRegistrationStrategy>();
您可能还必须了解如何 InterceptorRegistrationStrategy
, AutoNotifyInterceptorRegistrationStrategy
和MethodInterceptorRegistrationStrategy
工作,以便您可以创建一个有效且无副作用的实现。
(这不会取代拦截扩展,而只是扩展它)。
还有一个 stackoverflow 答案涵盖了可能有用的自定义策略:Ninject Intercept any method with certain attribute?
或者当然您可以使用其他方法之一来进行拦截:
- 使用绑定(bind),为整个类型定义拦截,如
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"));
(另请参阅 Interception with ninject )
关于c# - Ninject:通过属性进行拦截,而不从 InterceptAttribute 派生,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26102566/