views:

10

answers:

1

Based on the documentation for Castle.Core.InterceptorAttribute, I am trying to make this simple test pass, and am having no luck:

using NUnit.Framework;
using Castle.DynamicProxy;
using Castle.Core;
using Castle.MicroKernel;
using Castle.MicroKernel.Registration;


public interface IIntercepted { string get(); }

[Interceptor(typeof(TestInterceptor))]
public class Intercepted : IIntercepted
{
    public virtual string get() { return "From Service"; }
}

public class TestInterceptor : IInterceptor
{
    public void Intercept(IInvocation invocation)
    {
        invocation.Proceed();
        invocation.ReturnValue = "From Proxy";
    }
}
[TestFixture]
public class TestFixture
{
    [Test]
    public void Test_interception()
    {
        var container = new DefaultKernel();
        container.Register(
            Component.For<TestInterceptor>().LifeStyle.Transient,
            Component.For<IIntercepted>().ImplementedBy<Intercepted>());

        var instance = container.Resolve<IIntercepted>();
        Assert.That(instance.get(), Is.EqualTo("From Proxy"));
    }
}

In stepping through the tests, instance is not a proxy and get() returns "From Service". It seems to me that in this case, I should not need to make get() virtual, but did so just to be sure. I have the feeling I am missing something obvious and fundamental here, like is there a facility that needs to be registered here to make the container aware of the Interceptor attribute? I can't find any documentation to that effect. Can someone tell me what I am doing wrong?

I am using Castle version 2.5 and the 4.0 version of the .Net Framework.

+1  A: 

If you're going to use the DefaultKernel directly, you have to set up the proxy factory:

var container = new DefaultKernel {ProxyFactory = new DefaultProxyFactory()};

Otherwise, just use WindsorContainer instead (recommended).

BTW: you don't need to make the method virtual in the impl class in this case.

Mauricio Scheffer

related questions