加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – Castle Windsor拦截来自班级内的方法

发布时间:2020-12-15 23:31:07 所属栏目:百科 来源:网络整理
导读:我们在Castle Windsor容器中注册了组件,就像这样 void RegisterComponentTInterface,TImplementation() { var component = Component.ForTInterface().ImplementedByTImplementation(); component.InterceptorsSomeInterceptor(); container.Register(compon
我们在Castle Windsor容器中注册了组件,就像这样

void RegisterComponent<TInterface,TImplementation>() {
    var component = Component.For<TInterface>().ImplementedBy<TImplementation>();
    component.Interceptors<SomeInterceptor>();
    container.Register(component);
}

然而,我们遇到的问题是,当我们从类中进行方法调用时,它不会被截获.例如,我们有类似的组件

ServiceA : IService {

    public void MethodA1() {
        // do some stuff
    }

    public void MethodA2() {
        MethodA1();
    }

}

如果我们从其他类中调用MethodA2或MethodA1方法,则它会被截获,但是当从MethodA2调用时,MethodA1显然不会被截获,因为调用来自类中.

我们在解决方案Castle Dynamic Proxy not intercepting method calls when invoked from within the class中找到了类似的情况
然而,该解决方案使用new运算符来创建组件和代理,这在我们的情况下不适合,因为我们使用容器.我们可以像上面那样使用这个解决方案吗?还是有其他方法来解决这个问题?

解决方法

要从MethodA2调用MethodA1时进行拦截,您需要使用基于继承的拦截(这是因为您使用此引用进行调用).

要使基于继承的拦截成为可能,首先需要使MethodA1和MethodA2成为虚拟.

然后你可以像这样进行容器注册:

container.Register(Component.For<ServiceA>().Interceptors<SomeInterceptor>());
container.Register(Component.For<IService>().UsingFactoryMethod(c => c.Resolve<ServiceA>()));

首先将您的服务注册为自身应用拦截器(这将在服务上添加基于继承的拦截).然后,您可以注册将使用先前注册的服务的接口.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读