Getting SNAP(AOP), NInject and ASP.Net MVC 3 worki

2019-04-02 15:05发布

问题:

Has anyone got the SNAP AOP framework working with MVC 3 and Ninject.

The samples given when adding Snap using NuGet to an MVC 3 project don't specifcally work well with a previously added NInject package. I have tried to get it working based on the normal NInject approach but just cannot get it to actually intercept!

Can anyone show how to do this in code please?

回答1:

I figured it out with the latest version of Ninject through NuGet which now adds a class call NinjectMVC3 in a new AppStart folder in the MVC3 application.

The code I used is as folows: In the automatically created NinjectMVC3.cs CreateKernel() method:-

         private static IKernel CreateKernel()
        {
            // Wire it up with AOP
            NinjectAopConfiguration.NinjectAopConfigure();

            //var kernel = new StandardKernel(); // Removed

            RegisterServices(NinjectAopConfiguration._container.Kernel);

            return NinjectAopConfiguration._container.Kernel;
        }

I also wired up Ninject for the various injection targets in RegisterServices() method.

Next I took the sample code generated by NuGet when adding SNAP.Ninject to the MVC 3 application, renamed it NinjectAOP.cs and made it look like this:

 public static class NinjectAopConfiguration
    {
        public readonly static NinjectAspectContainer _container;

static NinjectAopConfiguration() { _container = new NinjectAspectContainer(); } public static void NinjectAopConfigure() { SnapConfiguration.For(_container).Configure(c => { c.IncludeNamespace("MyNamespace.Model.*"); c.Bind<ExceptionLoggingInterceptor>().To<ExceptionLoggingAttribute>(); }); } }

I also needed to do an assembly binding redirect for Ninject as follows because there is an assembly version conflict somewhere for Ninject:

I hope this helps someone.

I invite anyone to have a look and see if they can improve this please.