CompliationLock throws HttpException when register

2019-03-04 16:49发布

The moment I added a unit test to my ASP.NET MVC application to test some of the area routing, I got an HttpException coming out of the System.Web.Complication.CompilationLock type initializer with the following stack trace.

System.Web.HttpException : The type initializer for 'System.Web.Compilation.CompilationLock' threw an exception.
  ----> System.TypeInitializationException : The type initializer for 'System.Web.Compilation.CompilationLock' threw an exception.
  ----> System.NullReferenceException : Object reference not set to an instance of an object.
at System.Web.Compilation.BuildManager.ReportTopLevelCompilationException()
at System.Web.Compilation.BuildManager.EnsureTopLevelFilesCompiled()
at System.Web.Compilation.BuildManager.GetReferencedAssemblies()
at System.Web.Mvc.BuildManagerWrapper.System.Web.Mvc.IBuildManager.GetReferencedAssemblies()
at System.Web.Mvc.TypeCacheUtil.FilterTypesInAssemblies(IBuildManager buildManager, Predicate`1 predicate)
at System.Web.Mvc.TypeCacheUtil.GetFilteredTypesFromAssemblies(String cacheName, Predicate`1 predicate, IBuildManager buildManager)
at System.Web.Mvc.AreaRegistration.RegisterAllAreas(RouteCollection routes, IBuildManager buildManager, Object state)
at System.Web.Mvc.AreaRegistration.RegisterAllAreas(Object state)
at System.Web.Mvc.AreaRegistration.RegisterAllAreas()
at StpWeb.MvcApplication.RegisterRoutes(RouteCollection routes) in Global.asax.cs: line 16
at StpWeb.Tests.RoutesTest.TestFixtureSetUp() in RoutesTest.cs: line 11
--TypeInitializationException
at System.Web.Compilation.CompilationLock.GetLock(ref Boolean gotLock)
at System.Web.Compilation.BuildManager.EnsureTopLevelFilesCompiled()
--NullReferenceException
at System.Web.Compilation.CompilationLock..cctor()

1条回答
▲ chillily
2楼-- · 2019-03-04 16:59

For anyone else that followed the MVC Areas tutorials on MSDN, you will find an issue if you ever add unit tests to the web application you created.

It tells you to add AreaRegistration.RegisterAllAreas() to the RegisterRoutes method. Unfortunately, that is a static method that gets upset when called from unit tests.

Instead, register areas within Application_Start, right before the RegisterRoutes call you just modified. If you call RegisterRoutes first, UrlParameter.Optional appears to stop working in area routes (keeps working in non-area routes, though).

protected void Application_Start() {
        AreaRegistration.RegisterAllAreas();
        RegisterRoutes(RouteTable.Routes);
}
查看更多
登录 后发表回答