我正在尝试使用EntLib Logging构建我们的日志框架,并使用use属性来指示应记录哪个类/方法。所以我认为拦截将是一个不错的选择。我是Ninject和Interception的超级菜鸟,我正在Innovatian Software关注如何通过属性使用拦截的教程。但是当我运行应用程序时,从未调用过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");
}
}
答案 0 :(得分:1)
我想通了,我错过了我要禁用自动模块加载并手动将DynamicProxy2Module加载到内核的部分。这是对代码的更改:
//var kernel = new StandardKernel(); //Automatic Module Loading doesn't work
var kernel = new StandardKernel(new NinjectSettings() { LoadExtensions = false }, new DynamicProxy2Module());
希望这有助于其他人。