4

I am using Ninject interception to log errors on some of my methods. My interception class looks like this

public class ErrorLoggingInterceptor : IInterceptor
{
    private readonly ILogFactory _logFactory;

    public ErrorLoggingInterceptor(ILogFactory logFactory)
    {
        _logFactory = logFactory;
    }

    public void Intercept(IInvocation invocation)
    {
        try
        {
            invocation.Proceed();
        }
        catch (Exception e)
        {
            var sb = new StringBuilder();                
            sb.AppendFormat("Executing {0}.{1} ",invocation.Request.Method.DeclaringType.Name,invocation.Request.Method.Name);               
            sb.AppendFormat(" {0} caught: {1})", e.GetType().Name, e.Message);
            _logFactory.Error(sb.ToString());
        }
    }
}

This interceptor class works just fine but there are a few problems I came across.

  1. invocation.Request.Method.DeclaringType.Name gives me the name of the interface, how to get the name of the real impementing class?

  2. is there a way to get the argument values? I can get the parameter names using invocation.Request.Method.GetParameters but I did not found a way to get the actual values

  3. my interceptor is intended to "swallow" exceptions. It works on void methods, but is there a way to make it work on non-void methods providing a default value as the result? Say I have a bool DoSomething(..) and when it fails with exception I want it to look like the method returned false.
4

2 回答 2

6

您说的是 Ninject,但我假设您只对 Castle Dynamic Proxy 的功能感兴趣,IInvocation您的意思是Castle.DynamicProxy.IInvocation.

  1. invocation.TargetType.Name
  2. invocation.Arguments
  3. invocation.ReturnValue- 发生异常时可以设置

https://github.com/castleproject/Core/blob/master/src/Castle.Core/DynamicProxy/IInvocation.cs

当谈到 Ninject 扩展时,我会期待类似的东西(但是,我从未使用过它):

  1. invocation.Request.Target.GetType().Name
  2. invocation.Request.Arguments
  3. invocation.ReturnValue

https://github.com/ninject/ninject.extensions.interception/blob/master/src/Ninject.Extensions.Interception/IInvocation.cs https://github.com/ninject/ninject.extensions.interception/blob/master /src/Ninject.Extensions.Interception/Request/IProxyRequest.cs

于 2013-07-20T18:29:09.463 回答
2

有没有办法获取参数值?我可以使用 invocation.Request.Method.GetParameters 获取参数名称,但我没有找到获取实际值的方法

对于参数,我创建了一个小助手,它将为您提供与值映射的参数名称,然后可以将其转换为字典。

    private IEnumerable<KeyValuePair<string, object>> MapParameters(object[] arguments, ParameterInfo[] getParameters)
    {
        for (int i = 0; i < arguments.Length; i++)
        {
            yield return new KeyValuePair<string, object>(getParameters[i].Name, arguments[i]);
        }
    }

用法如下所示:

        var mappedParameters = MapParameters(invocation.Arguments, invocation.Method.GetParameters())
            .ToDictionary(x => x.Key, x => x.Value?.ToString());

例子

方法签名: Get(int id)

用法:获取(1)

输出:{[id, 1]}

于 2015-03-07T15:39:04.060 回答