2011-12-07 83 views
1

我想使用EntLib日誌記錄和使用屬性來構建我們的日誌框架,以指示應該記錄哪個類/方法。所以我認爲攔截將是一個不錯的選擇。我是Ninject和Interception的超級noob,我在Innovatian Software上關注如何使用攔截通過屬性的教程。但是當我運行該應用程序時,BeforeInvoke和AfterInvoke從未被調用過。請幫助,謝謝!無法通過屬性獲得Ninject-Interception的工作,我做錯了什麼?

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"); 
     } 
    } 

回答

1

我想通了,我錯過了在那裏我已經禁用自動模塊的加載和手動加載DynamicProxy2Module到內核的部分。以下是對代碼的更改:

//var kernel = new StandardKernel(); //Automatic Module Loading doesn't work 
var kernel = new StandardKernel(new NinjectSettings() { LoadExtensions = false }, new DynamicProxy2Module()); 

希望這可以幫助別人。

相關問題