1

EntLib Logging を使用してロギング フレームワークを構築し、属性を使用して、どのクラス/メソッドをログに記録するかを指定しようとしています。だから私はインターセプトが良い選択だと思います。私は Ninject と傍受の超初心者であり、属性を介して傍受を使用する方法に関する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");
        }
    }
4

1 に答える 1

1

自動モジュールのロードを無効にして、DynamicProxy2Module をカーネルに手動でロードする必要がある部分を見逃していました。コードの変更は次のとおりです。

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

これが他の誰かを助けることを願っています。

于 2011-12-07T21:21:56.147 に答える