【问题标题】:Asp.net MVC 3 not working with Ninject after upgrade from MVC 2?从 MVC 2 升级后,Asp.net MVC 3 不能与 Ninject 一起使用?
【发布时间】:2011-10-06 00:41:53
【问题描述】:

我有一个使用 Asp.net MVC2 的 Web 应用程序。我将它升级到 MVC 3,现在我发现 OutputCache 功能不再工作了。我创建了一个简单的测试操作,如下所示。

 [OutputCache(Duration = 1000000, VaryByParam = "none")]
 public virtual ActionResult CacheTest(string name)
  {
     string message = string.Format("{0}: Time is {1}", name, DateTime.Now.ToLongTimeString());
     ViewData.Add("Message", message);
     return View();
  }

这总是给出当前时间,表明它未缓存。我在这里遗漏了什么吗?

更多信息:如果我创建一个新的 Mvc3 应用程序,它可以正常工作。仅在升级后的应用程序中出现此问题。

更新:我也在使用 Ninject。如果我停止使用 Ninject OutputCache 开始工作。

public class MvcApplication : System.Web.HttpApplication
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

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

        }

        protected void Application_Start()
        {
            RegisterDependencyResolver();

            AreaRegistration.RegisterAllAreas();

            RegisterRoutes(RouteTable.Routes);
        }

        protected void RegisterDependencyResolver()
        {
            var kernel = CreateKernel();
            DependencyResolver.SetResolver(new NinjectDependencyResolver(kernel));
        }

        protected IKernel CreateKernel()
        {
            return new StandardKernel();
        }
    }

【问题讨论】:

  • 很奇怪,我无法重现该问题。缓存对我有用。
  • 如果我创建一个新的 Mvc3 应用程序,它工作正常。仅在升级后的应用程序中出现此问题。
  • 这一切都没有意义。对我来说,这 a) 不能被复制 b) 只是没有意义 - Ninject 只是与OutputCacheAttribute 无关,所以一定有一些东西搞砸了,比如有多个版本的 Ninject 或 MVC 在玩。另见groups.google.com/forum/?fromgroups=#!topic/ninject/NtsBWNS4MJs

标签: asp.net asp.net-mvc asp.net-mvc-3 caching ninject


【解决方案1】:

在 ASP.NET MVC 3 中使用 Ninject 的正确和推荐方法如下:

  1. 安装ninject.mvc3 NuGet 包。这将确保您获得与 ASP.NET MVC 3 兼容的最新版本。

  2. 安装后,它将在您的项目中添加一个 App_Start/NinjectMVC3.cs 文件,它位于 RegisterServices 方法中,您将注册您的 Ninject 模块:

    private static void RegisterServices(IKernel kernel)
    {
        var modules = new INinjectModule[]
        {
            // your modules here
        };
        kernel.Load(modules);
    }        
    
  3. 从您的 Global.asax 中删除所有 Ninject 特定代码,包括任何 NinjectDependencyResolver

尝试按照这些步骤操作,也许您的问题会得到解决。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-12-18
    • 1970-01-01
    • 2011-06-24
    • 1970-01-01
    • 1970-01-01
    • 2012-11-30
    • 2016-10-20
    • 2011-07-24
    相关资源
    最近更新 更多