城堡拦截器与流畅的接口

jon*_*nii 1 c# castle-windsor fluent-interface iinterceptor

我正在尝试获得一个我写的工作拦截器,但由于某种原因,当我请求我的组件时它似乎并没有实例化拦截器.我正在做这样的事情(原谅我,如果这不完全编译,但你应该得到这个想法):

container.Register(
    Component.For<MyInterceptor>().LifeStyle.Transient,
    AllTypes.Pick().FromAssembly(...).If(t => typeof(IView).IsAssignableFrom(t)).
    Configure(c => c.LifeStyle.Is(LifestyleType.Transient).Named(...).
                   Interceptors(new InterceptorReference(typeof(MyInterceptor)).
    WithService.FromInterface(typeof(IView)));
Run Code Online (Sandbox Code Playgroud)

我在断路器的构造函数中放置了断点,它似乎根本没有实例化它.

在过去,我使用XML配置注册了我的拦截器,但我很想使用流畅的界面.

任何帮助将不胜感激!

Mau*_*fer 6

我觉得你在滥用WithService.FromInterface.文档说:

使用实现来查找子接口.例如:如果您有IService和IProductService:ISomeInterface,IService,ISomeOtherInterface.当您调用FromInterface(typeof(IService))时,将使用IProductService.当您想要注册所有服务但又不想指定所有服务时很有用.

你也错过了InterceptorGroup Anywhere.这是一个工作样本,我从样本中尽可能少地改变它以使其工作:

[TestFixture]
public class PPTests {
    public interface IFoo {
        void Do();
    }

    public class Foo : IFoo {
        public void Do() {}
    }

    public class MyInterceptor : IInterceptor {
        public void Intercept(IInvocation invocation) {
            Console.WriteLine("intercepted");
        }
    }

    [Test]
    public void Interceptor() {
        var container = new WindsorContainer();

        container.Register(
            Component.For<MyInterceptor>().LifeStyle.Transient,
            AllTypes.Pick()
                .From(typeof (Foo))
                .If(t => typeof (IFoo).IsAssignableFrom(t))
                .Configure(c => c.LifeStyle.Is(LifestyleType.Transient)
                                    .Interceptors(new InterceptorReference(typeof (MyInterceptor))).Anywhere)
                .WithService.Select(new[] {typeof(IFoo)}));

        container.Resolve<IFoo>().Do();
    }
}
Run Code Online (Sandbox Code Playgroud)