asp.net-mvc-3 – 使用Ninject 2.2全局动作过滤器的MVC 3依赖注入

我正在尝试使用ASP.NET MVC 3和Ninject 2.2将logger对象注入自定义ActionFilterAttribute.

如果我使用自定义属性标记每个控制器,我能够使其工作.

但是,如果我从控制器中删除属性修饰并尝试使用全局操作过滤器,则无法使其工作.

这是代码

在App_Start下 – NinjectMVC3.cs

using NinjectTest.Abstract;
using NinjectTest.Concrete;

[assembly:      WebActivator.PreApplicationStartMethod(typeof(NinjectTest.App_Start.NinjectMVC3),"Start")]
[assembly: WebActivator.ApplicationShutdownMethodAttribute(typeof(NinjectTest.App_Start.NinjectMVC3),"Stop")]

namespace NinjectTest.App_Start
{
using Microsoft.Web.Infrastructure.DynamicModuleHelper;

using Ninject;
using Ninject.Web.Mvc;

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<ILogger>().To<Log4NetLogger>();
    }       
}

}

的Global.asax.cs

using System.Web.Routing;
using NinjectTest.Attributes;

namespace NinjectTest
{
public class MvcApplication : HttpApplication
{
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new TestLoggingAttribute());
        filters.Add(new HandleErrorAttribute());
    }

    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            "Default",// Route name
            "{controller}/{action}/{id}",// URL with parameters
            new { controller = "Home",action = "Index",id = UrlParameter.Optional } // Parameter defaults
        );

    }

    protected void Application_Start()
    {
        log4net.Config.XmlConfigurator.Configure();

        AreaRegistration.RegisterAllAreas();

        RegisterGlobalFilters(GlobalFilters.Filters);
        RegisterRoutes(RouteTable.Routes);
    }
}

}

TestLoggingAttribute.cs

using System.Web.Mvc;
using Ninject;
using NinjectTest.Abstract;

namespace NinjectTest.Attributes
{
public class TestLoggingAttribute : ActionFilterAttribute
{
    [Inject]
    public ILogger _logger { get; set; }

    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {

        var controller = filterContext.RouteData.Values["controller"];
        var action = filterContext.RouteData.Values["action"];

        _logger.Info("controller: " + controller + " action: " + action);

        base.OnActionExecuted(filterContext);
    }     

  }
}

HomeController.cs

using System.Web.Mvc;
using NinjectTest.Attributes;

namespace NinjectTest.Controllers
{
//[TestLogging]
public class HomeController : Controller
{
    public ActionResult Index()
    {
        ViewBag.Message = "Welcome to ASP.NET MVC!";

        return View();
    }

    public ActionResult About()
    {
        return View();
    }

}
}

就像我提到的,如果我取消注释控制器中的[TestLogging]属性,这一切都有效.但是,我想使用全局过滤器.
有人可以帮我吗?

解决方法

您可能会发现 following blog post很有用.所以在您的RegisterServices方法中只需:
private static void RegisterServices(IKernel kernel)
{
    kernel.Bind<ILogger>().To<Log4NetLogger>();
    kernel.BindFilter<TestLoggingAttribute>(FilterScope.Global,0);
}

并将BindFilter扩展方法纳入范围,不要忘记添加正确的using指令:

using Ninject.Web.Mvc.FilterBindingSyntax;

相关文章

项目要求通过网站上传大文件,比如视频文件,通过摸索实现了文件分片来上传,然后后台进行合并。 使用了...
安装新版本的Nginx(vim /etc/yum.repos.d/nginx.repo) [nginx-stable] name=nginx stable repo baseu...
什么是 SignalR&#160;ASP.NET Core ASP.NET Core SignalR 是一种开放源代码库,可简化将实时 web 功...
在Windows下使用Docker,我们选择Docker Desktop这个软件,非常方便。 ## Docker Desktop介绍及安装 Do...
项目开始设计的是运行在windows下,所以一开始采用的是windows服务模式来获取多媒体文件信息,后来要求...
银河麒麟高级服务器操作系统V10是针对企业级关键业务,适应虚拟化、云计算、大数据、工业互联网时代对主...