c# - Ninject:通过属性进行拦截,而不从 InterceptAttribute 派生

标签 c# dependency-injection attributes ninject aop

我正在寻找一种方法,使用 Ninject 将拦截器连接到基于特定属性的方法调用。 Ninject 提供了 InterceptAttribute 基类来执行此操作,这很简洁,但是我想使用自定义属性来实现此目的。原因是我想用业务相关的属性来装饰某些领域服务接口(interface),所以我不能让任何东西与框架紧密耦合。

这可能吗?

最佳答案

您可以从 InterceptorRegistrationStrategy 派生并覆盖 Execute(IPlan plan)方法(可能还有 RegisterClassInterceptors )来使用您自己的属性类型而不是 ninject 的 InterceptAttribute .

然后您需要将实现注册为内核组件:

this.Kernel.Components.Add<IPlanningStrategy, MyInterceptorRegistrationStrategy>();

您可能还必须了解如何 InterceptorRegistrationStrategy , AutoNotifyInterceptorRegistrationStrategyMethodInterceptorRegistrationStrategy工作,以便您可以创建一个有效且无副作用的实现。 (这不会取代拦截扩展,而只是扩展它)。

还有一个 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/

相关文章:

c# - 如何解析 Orchard CMS 中的对象?

c# - 如何将多个 HttpClient 参数传递/注入(inject)到类型化的 HttpClientClass?

jsf - 在扩展现有 JSF 组件的复合组件中继承组件属性

c# - 以编程方式向方法或参数添加属性

C# 泛型类型约束

c# - 将 IEnumerable ViewModel 传递给 View

c# - 使用空参数调用 Type.MakeGenericType()

c# - 如何使正则表达式只匹配完全匹配项?

java - 使用Guice : No implementation bounded

r - 如果对象名称在变量中,如何设置对象的特定属性?