我正在使用IInterceptor拦截某些类中的方法调用。 拦截器设置如下:public class InstrumentationInterceptor:IInterceptor { public InstrumentationInterceptor() { Measure.Configure(new StatsdConfig()); }
public void Intercept(IInvocation invocation)
{
var instrumentationId = new StringBuilder();
instrumentationId.Append(typeof(Program).Namespace.Replace(".", string.Empty).ToLower());
instrumentationId.Append(".");
instrumentationId.Append("response");
instrumentationId.Append(".");
// The following will split the camel case simple name of the proxied class,
// where 'Consumer' suffix has been removed, and also convert to lower case
instrumentationId.Append(Regex.Replace(invocation.TargetType.Name.Replace("Consumer", string.Empty), "(\\B[A-Z])", "_$1").ToLowerInvariant());
instrumentationId.Append(".");
instrumentationId.Append("duration");
using (
Measure.StartTimer(instrumentationId.ToString()))
{
invocation.Proceed();
Measure.Counter(instrumentationId.ToString(), 1);
}
}
}
然后在Autofac模块中将其连接起来:
var builder = new ContainerBuilder();
builder.RegisterType<DataConsumer>().
As<IConsumer<DataRequest>>().
EnableInterfaceInterceptors().
InterceptedBy(typeof (InstrumentationInterceptor));
builder.Build();
我正在使用它来测量所花费的时间并计算调用此方法的实例。我希望能够将其推送到我拥有的外部库,但是我将失去获取调用程序的命名空间的能力。有没有办法使用IInvocation来到目标命名空间?
对此的任何想法都会有用。
感谢。
答案 0 :(得分:2)
您可以在调用中使用GetConcreteMethodInvocationTarge
方法来获取您实际拦截的MethodInfo
实例。
GetConcreteMethodInvocationTarget
:
- 摘要:返回
IInvocation.MethodInvocationTarget
的具体实例,其中任何通用参数都绑定到实际类型。对于接口代理,这将指向目标类上的System.Reflection.MethodInfo。
- 返回:
IInvocation.MethodInvocationTarget
的具体实例化,如果不是通用方法,则为IInvocation.MethodInvocationTarget
。
使用MethodInfo
,您可以获取类型,然后获取命名空间。
String namespace = invocation.GetConcreteMethodInvocationTarget().DeclaringType.Namespace;
另一个解决方案是使用InvocationTarget
属性,然后调用.GetType()
方法来检索截获的类型,但在某些复杂的情况下,它可能无效。
String namespace = invocation.InvocationTarget.GetType().Namespace;
答案 1 :(得分:0)
好吧,这比我想象的容易。
invocation.InvocationTarget.ToString()
为您提供目标类的命名空间;顾名思义:)
由于