【问题标题】:Ninject: Intercept by attribute without deriving from InterceptAttributeNinject:按属性拦截而不从 InterceptAttribute 派生
【发布时间】:2014-09-30 22:56:41
【问题描述】:

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

这可能吗?

【问题讨论】:

    标签: c# dependency-injection attributes ninject aop


    【解决方案1】:

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

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

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

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

    还有一个涵盖自定义策略的 stackoverflow 答案可能有用:Ninject Intercept any method with certain attribute?

    当然,您也可以使用其他方法之一进行拦截:

    • 使用绑定,为整个类型定义拦截,例如Bind&lt;IFoo&gt;().To&lt;Foo&gt;().Intercept().With&lt;MyInterceptor&gt;(),并让MyInterceptor 检查它是否应该拦截给定的方法。
    • 使用约定 API 或自己编写类似的东西,搜索所有自定义拦截属性,然后使用以下语法:
    Kernel.InterceptAround<CustomerService>(
        s=>s.GetAllCustomers(),
        invocation =>logger.Info("Retrieving all customers..."),
        invocation =>logger.Debug("Customers retrieved"));
    

    (另见Interception with ninject

    【讨论】:

      猜你喜欢
      • 2013-03-08
      • 2013-08-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多