Couldn't get Ninject-Interception via Attributes to work, what did I do wrong?

1.1k views Asked by At

I'm trying build out our logging framework using EntLib Logging and use attribute to indicate which class/method should be logged. So I think Interception would be a good choice. I'm a super noob to Ninject and Interception and I's following the tutorial at Innovatian Software on how to use interception via attributes. But when I run the app, BeforeInvoke and AfterInvoke was never called. Help Please, Thank You!

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

There are 1 answers

0
hwong668 On

I figured it out, I missed the part where I've to disable auto module loading and manually load the DynamicProxy2Module to the kernel. Here's the change to the code:

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

Hope this help someone else.