我正在尝试使用EntLib logging构建我们的日志框架,并使用属性来指示应该记录哪个类/方法。所以我觉得拦截是个不错的选择。我是一个超级菜鸟的Ninject和拦截,我在创新软件的教程,如何使用拦截通过属性。但是当我运行应用程序时,BeforeInvoke和AfterInvoke从未被调用过。请帮忙,谢谢!
using System;
using System.Diagnostics;
using System.Collections.Generic;
using Castle.Core;
using Ninject;
using Ninject.Extensions.Interception;
using Ninject.Extensions.Interception.Attributes;
using Ninject.Extensions.Interception.Request;
class Program
{
static void Main(string[] args)
{
var kernel = new StandardKernel();
kernel.Bind<ObjectWithMethodInterceptor>().ToSelf();
var test= kernel.Get<ObjectWithMethodInterceptor>();
test.Foo();
test.Bar();
Console.ReadLine();
}
}
public class TraceLogAttribute : InterceptAttribute
{
public override IInterceptor CreateInterceptor(IProxyRequest request)
{
return request.Context.Kernel.Get<TimingInterceptor>();
}
}
public class TimingInterceptor : SimpleInterceptor
{
readonly Stopwatch _stopwatch = new Stopwatch();
protected override void BeforeInvoke(IInvocation invocation)
{
Console.WriteLine("Before Invoke");
_stopwatch.Start();
}
protected override void AfterInvoke(IInvocation invocation)
{
Console.WriteLine("After Invoke");
_stopwatch.Stop();
string message = string.Format("Execution of {0} took {1}.",
invocation.Request.Method,
_stopwatch.Elapsed);
Console.WriteLine(message);
_stopwatch.Reset();
}
}
public class ObjectWithMethodInterceptor
{
[TraceLog] // intercepted
public virtual void Foo()
{
Console.WriteLine("Foo - User Code");
}
// not intercepted
public virtual void Bar()
{
Console.WriteLine("Bar - User Code");
}
}
我弄清楚了,我错过了我必须禁用自动模块加载和手动加载DynamicProxy2Module到内核的部分。下面是对代码的修改:
//var kernel = new StandardKernel(); //Automatic Module Loading doesn't work
var kernel = new StandardKernel(new NinjectSettings() { LoadExtensions = false }, new DynamicProxy2Module());