castle-windsor Interceptors Interceptors doesn't have to call Proceed every time


Example

Interceptors are a good tool for implementing cross-cutting concerns such as logging or authentication. Let's say we have a following service:

public interface IService
{
    string CreateOrder(NetworkCredential credentials, Order orderToCreate);
    string DeleteOrder(NetworkCredential credentials, int orderId);
}

public class Service : IService
{
    public string CreateOrder(NetworkCredential credentials, Order orderToCreate)
    {
        // ...

        return "Order was created succesfully.";
    }

    public string DeleteOrder(NetworkCredential credentials, int orderId)
    {
        // ...

        return "Order was deleted succesfully.";
    }
}

We can create following interceptor:

public class AuthorizationInterceptor : IInterceptor
{
    public void Intercept(IInvocation invocation)
    {
        var userCredentials = invocation.Arguments[0] as NetworkCredential;
        
        if (userCredentials.UserName == "tom" && userCredentials.Password == "pass123")
            // this ^ verification is obviously silly, never do real security like this
        {
            invocation.Proceed();
        }
        else
        {
            invocation.ReturnValue = $"User '{userCredentials.UserName}' was not authenticated.";
        }
    }
}

That can be registered and utilized like this:

var container = new WindsorContainer();
container.Register(
    Component.For<AuthorizationInterceptor>(),
    Component.For<IService>().ImplementedBy<Service>().Interceptors<AuthorizationInterceptor>());

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

System.Diagnostics.Debug.Assert(
    service.DeleteOrder(new NetworkCredential { UserName = "paul", Password = "pass321" }, 8)
        == "User 'paul' was not authenticated.");

System.Diagnostics.Debug.Assert(
    service.CreateOrder(new NetworkCredential { UserName = "tom", Password = "pass123" }, new Order())
        == "Order was created succesfully.");

The important lesson is that interceptor can decide to pass call and if it doesn't, it can supply arbitrary return value using ReturnValue property.