ASP.NET MVC 3 and Global Filter Injection

前端 未结 1 768
别那么骄傲
别那么骄傲 2021-02-09 12:54

Hello am an trying to implement a global filter with injection. The filter looks like this.

public class WikiFilter : IActionFilter
{
    private IWikiService se         


        
相关标签:
1条回答
  • 2021-02-09 13:40

    I would recommend you using the ~/App_Start/NinjectMVC3.cs file to configure the Ninject kernel:

    [assembly: WebActivator.PreApplicationStartMethod(typeof(AppName.App_Start.NinjectMVC3), "Start")]
    [assembly: WebActivator.ApplicationShutdownMethodAttribute(typeof(AppName.App_Start.NinjectMVC3), "Stop")]
    
    namespace AppName.App_Start
    {
        using System.Web.Mvc;
        using Microsoft.Web.Infrastructure.DynamicModuleHelper;
        using Ninject;
        using Ninject.Web.Mvc;
        using Ninject.Web.Mvc.FilterBindingSyntax;
    
        public static class NinjectMVC3
        {
            private static readonly Bootstrapper bootstrapper = new Bootstrapper();
    
            /// <summary>
            /// Starts the application
            /// </summary>
            public static void Start()
            {
                DynamicModuleUtility.RegisterModule(typeof(OnePerRequestModule));
                bootstrapper.Initialize(CreateKernel);
            }
    
            /// <summary>
            /// Stops the application.
            /// </summary>
            public static void Stop()
            {
                bootstrapper.ShutDown();
            }
    
            /// <summary>
            /// Creates the kernel that will manage your application.
            /// </summary>
            /// <returns>The created kernel.</returns>
            private static IKernel CreateKernel()
            {
                var kernel = new StandardKernel();
                RegisterServices(kernel);
                return kernel;
            }
    
    
            /// <summary>
            /// Load your modules or register your services here!
            /// </summary>
            /// <param name="kernel">The kernel.</param>
            private static void RegisterServices(IKernel kernel)
            {
                kernel.Bind<DataContext>().ToSelf().InRequestScope();
                kernel.Bind<IWikiRepository>().To<WikiRepository>();
                kernel.Bind<IWikiService>().To<WikiService>();
                kernel.BindFilter<WikiFilter>(FilterScope.Global, 0);
            }
        }
    }
    

    and the Global.asax stays unchanged. By the way that's the default setup when you install the Ninject.MVC3 NuGet package.

    0 讨论(0)
提交回复
热议问题