【发布时间】:2014-09-30 22:56:41
【问题描述】:
我正在寻找一种使用 Ninject 将拦截器连接到基于某个属性的方法调用的方法。 Ninject 提供了InterceptAttribute 基类,这很简洁,但是我想使用自定义属性来实现这一点。原因是我想用业务相关的属性来装饰某些领域服务接口,所以我不能让任何东西与框架紧密耦合。
这可能吗?
【问题讨论】:
标签: c# dependency-injection attributes ninject aop
我正在寻找一种使用 Ninject 将拦截器连接到基于某个属性的方法调用的方法。 Ninject 提供了InterceptAttribute 基类,这很简洁,但是我想使用自定义属性来实现这一点。原因是我想用业务相关的属性来装饰某些领域服务接口,所以我不能让任何东西与框架紧密耦合。
这可能吗?
【问题讨论】:
标签: c# dependency-injection attributes ninject aop
您可以从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<IFoo>().To<Foo>().Intercept().With<MyInterceptor>(),并让MyInterceptor 检查它是否应该拦截给定的方法。Kernel.InterceptAround<CustomerService>(
s=>s.GetAllCustomers(),
invocation =>logger.Info("Retrieving all customers..."),
invocation =>logger.Debug("Customers retrieved"));
【讨论】: