【发布时间】:2013-10-21 04:58:22
【问题描述】:
我试图了解Ninject.Extensions.Interception 3.0.0.8 如何为我的课程构建动态代理。我发现当我使用继承自 InterceptAttribute 的属性装饰我的具体类时,或者当我在绑定时使用 Intercept() 方法直接拦截时,Ninject 返回装饰类的动态代理而不是普通类型。
我有一个IPolicySearchPresenter 接口,我绑定到FlexPolicySearchPresenter 具体类型添加一个异常记录器拦截器:
Bind<IExceptionInterceptor>().To<ExceptionInterceptor>();
Bind<IPolicySearchPresenter>().To<FlexPolicySearchPresenter>().Intercept().With<IExceptionInterceptor>();
问题是当我检查该绑定的返回类型时:
var proxy = Kernel.Get<IPolicySearchPresenter>();
我得到Castle.Proxies.IPolicySearchPresenterProxy 的实例而不是FlexPolicySearchPresenterProxy
这给我的 FluorineFx 远程处理应用程序带来了问题。但是,如果我手动创建我的 Castle 代理:
ProxyGenerator generator = new ProxyGenerator();
//My presenter type
Type type = typeof(FlexPolicySearchPresenter);
//My presenter interface
var interfaceType = type.GetInterfaces().Single();
//Get my Interceptor from container. Notice that i had to
//change my Interceptor to implement IInterceptor from Castle libs,
// instead of Ninject IInterceptor
var excepInt = Kernel.Get<ExceptionInterceptor>();
//Manually get all my instances required by my presenter type Constructor
//ideally passed through Constructor Injection
var presenterSearchService = Kernel.Get<IPolicySearchService>();
var userAuthService = Kernel.Get<IUserAuthorizationService>();
//Create proxy, passing interceptor(s) and constructor arguments
var proxy = generator.CreateClassProxy(type, new object[] { presenterSearchService, userAuthService },
new IInterceptor[]
{
excepInt
});
//Ninject.Extensions.Interception.DynamicProxyModule
// I'm using directive ToConstant(..), and not To(..)
//Bind my interface to the new proxy
Bind(interfaceType).ToConstant(proxy).InThreadScope();
var proxy = Kernel.Get<IPolicySearchPresenter>();
返回的类型以Castle.Proxies.FlexPolicySearchPresenterProxy 的形式返回,这与我的远程实现完美配合。
问题是,我怎样才能让 Ninject.Interception 返回 FlexPolicySearchPresenterProxy 而不是 IPolicySearchPresenterProxy 的实例。
请注意,通过手动 Castle 方式,我以不同的方式绑定:
Bind(interfaceType).ToConstant(proxy).InThreadScope();
而不是ninject方式:
Bind<IPolicySearchPresenter>().To<FlexPolicySearchPresenter>().Intercept().With<IExceptionInterceptor>();
我是否需要更改在 Ninject 中进行绑定的方式才能获得正确的类型?
【问题讨论】:
-
您是否尝试过创建从 IPolicy.. 到 FlexPolicy and 的绑定,然后绑定 FlexPolicy .ToSelf().Intercept().With... ? (旁注:ninject instanciaties 拦截器每个类型一次,而不是每个代理实例一次)。
-
不,我没试过。今天早上我会试一试。感谢您的建议
-
我这样做了:
Bind<IPolicySearchPresenter>().To<FlexPolicySearchPresenter>();Bind<FlexPolicySearchPresenter>().ToSelf().Intercept().With<IExceptionInterceptor>();var proxy = Kernel.Get<IPolicySearchPresenter>();但是代理返回为FlexPolicySearchPresenter类型而不是FlexPolicySearchPresenterProxy并且拦截没有启动:( -
奇怪。 @FlexPolicySearchPresenter 有没有虚方法?顺便说一句,这里是动态代理实例化的 ninject 扩展代码:github.com/ninject/ninject.extensions.interception/blob/master/…(注意 if(targetType.IsInterface))
-
是的,我的演示者中有一个虚拟方法,我在其中抛出异常,以便我的拦截器管理它。我从 NuGet 下载了我正在使用的版本的 Ninject.Extensions.Interception 源代码,但无法将调试器附加到它,这将使事情变得更加清晰......
标签: c# ninject fluorinefx ninject-interception