Castle Windsor无法拦截为类实例注册的组件 [英] Castle Windsor Cannot Intercept Component Registered For A Class Instance

查看:62
本文介绍了Castle Windsor无法拦截为类实例注册的组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在拦截注册到类实例的组件时遇到问题.

I have problem intercepting a component registered to a class intance.

//this does not get intercepted
container.Register(Component.For<IService>().Instance(instanceService)
                                .Interceptors<Interceptor>());

如果我在不使用类实例的情况下注册组件,拦截器将起作用

Interceptor works if I register the component without using the class instance

//this get intercepted
container.Register(Component.For<IService>().ImplementedBy<SampleService>()
                         .Interceptors<Interceptor>());

这是错误还是故意的?

谢谢

这是单元测试代码.

    [Test]
    public void Test_Windsor_Interceptor_With_Instance_Component_Registration()
    {
        IService instanceService = new SampleService();

        var container = new WindsorContainer();
        container.Register(Component.For<Interceptor>());

        //this get intercepted
        container.Register(Component.For<IService>().ImplementedBy<SampleService>()
                            .Interceptors<Interceptor>());

        ////this does not get intercepted
        //container.Register(Component.For<IService>().Instance(instanceService)
        //                    .Interceptors<Interceptor>());

        var proxiedService = container.Resolve<IService>();

        proxiedService.DoSomething();


    }

    public class Interceptor : Castle.DynamicProxy.IInterceptor
    {
        public void Intercept(Castle.DynamicProxy.IInvocation invocation)
        {
            throw new System.NotImplementedException("Interceptor succesfully called but not implemented");
        }
    }

    public interface IService
    {
        void DoSomething();
    }

    public class SampleService : IService
    {
        public void DoSomething()
        {
            string dummy = string.Empty;
        }
    }

推荐答案

这是设计使然.如果要手动实例化对象,则不能指望Windsor连接拦截器.

It's by design. You can't expect Windsor to wire up an interceptor if you're manually instantiating the object.

这篇关于Castle Windsor无法拦截为类实例注册的组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆