Reputation: 52321
I'm trying to use Castle DynamicProxy, but the most basic piece of code inspired from tutorials such as this one fails.
In order to make things simpler, I've put all the code in one file, so it would be short enough to copy-paste here:
namespace UnitTests
{
using Castle.DynamicProxy;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
[TestClass]
public class DemoTests
{
[TestMethod]
public void TestHelloMethodThroughProxy()
{
var proxy = new ProxyGenerator().CreateClassProxy<Demo>(new DemoInterceptor());
var actual = proxy.SayHello();
var expected = "Something other";
Assert.AreEqual(expected, actual);
}
}
[Serializable]
public class DemoInterceptor : IInterceptor
{
public void Intercept(IInvocation invocation)
{
invocation.ReturnValue = "Something other";
}
}
public class Demo
{
public string SayHello()
{
return "Hello, World!";
}
}
}
The code consists of a single unit test which generates a proxy of a class, and then calls a method of this class through the proxy.
The proxy is intended to circumvent the call to the original method by simply assigning a result value, without calling the original method.
If I replace invocation.ReturnValue = "Something other";
by throw new NotImplementedException();
, the result of the test is still exactly the same, and the exception is not thrown, indicating that the code is probably not called. In debug mode, breakpoints within the Intercept
method are not reached either.
What do I need to do in order for the interceptors to be called?
Upvotes: 2
Views: 885
Reputation: 73452
Castle Windsor can intercept only interface or virtual members. Your Demo.SayHello
method is not marked as virtual and thus it is not intercepted.
Either mark the method as virtual or work with interfaces.
Refer Why can Windsor only intercept virtual or interfaced methods?
Upvotes: 2