Не удалось заставить работать Ninject-Interception через атрибуты, что я сделал не так? - PullRequest
1 голос
/ 07 декабря 2011

Я пытаюсь построить нашу структуру ведения журналов, используя EntLib Logging и использовать атрибут, чтобы указать, какой класс / метод должен регистрироваться.Поэтому я думаю, что перехват был бы хорошим выбором.Я супер нуб к 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");
        }
    }

1 Ответ

1 голос
/ 08 декабря 2011

Я понял, я пропустил часть, где я должен отключить автоматическую загрузку модуля и вручную загрузить DynamicProxy2Module в ядро. Вот изменение в коде:

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

Надеюсь, это поможет кому-то еще.

...