Question

I'm new to Ninject and I'm trying to intercept two methods inside a class. The first method gets intercepted. The first method calls the second method but the latter doesn't trigger the interceptor.

Is there a solution?

Here's some code:

public interface IJobMonitor
{
    void Run();

    JobCheck ManageJob(JobCheck job);
}

[LogAround]
public class JobMonitor : IJobMonitor {

  public virtual void Run(){
    //boilerplate
    var job = ManageJob(new JobCheck());
  }

  public virtual JobCheck ManageJob(JobCheck job) {
    //lots of good stuff
  }
}

public class LogAroundAttribute : InterceptAttribute
{
    public override IInterceptor CreateInterceptor(IProxyRequest request)
    {
        return request.Kernel.Get<LogAroundInterceptor>();
    }
}

public class LogAroundInterceptor : IInterceptor
{
    private readonly ILogger _logger;

    public LogAroundInterceptor(ILogger logger)
    {
        _logger = logger;
    }

    public void Intercept(IInvocation invocation)
    {
        var methodName = invocation.Request.Method.Name;
        try
        {

            var message = string.Format("Method {0} called", methodName);


            _logger.Info(message);
            invocation.Proceed();

            var endMessage = String.Format("Method {0} completed", methodName);
            _logger.Info(endMessage);
        }
        catch(Exception e)
        {
            var message = string.Format("Method {0} EXCEPTION occured: {1} ", methodName, e);
            _logger.Fatal(message);
            throw;
        }
    }

}
Was it helpful?

Solution

This is a limitation of the proxy implementation. A proxy is basically a dynamic class (object) wrapping the target. At runtime, all users of the target are accessing the proxy instead of the target. IInvocation.Proceed will finally forward the call to the target. When the target calls a method on itself,... well the target method is called directly without going through the proxy and the interceptors.

What you can do is adapt your implementation so that you don't need to intercept a method invoked on the target by the target. You could extract that method to another class which you could then proxy and intercept.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top