I get the following error randomly when running an ASP.NET MVC 2 project. This error occurs on different pages at different times. Cannot reproduce this error or identify pattern of when and on which page the error occurs.
System.Web.HttpException: Error executing child request for handler 'System.Web.Mvc.HttpHandlerUtil+ServerExecuteHttpHandlerWrapper ---> System.Web.HttpUnhandledException: Exception of type 'System.Web.HttpUnhandledException' was thrown. ---> System.NullReferenceException: Object reference not set to an instance of an object.
It happens on different pages
Example: (Trying to view a partial view)
System.Web.HttpException: Error executing child request for handler 'System.Web.Mvc.HttpHandlerUtil+ServerExecuteHttpHandlerWrapper'. ---> System.Web.HttpUnhandledException: Exception of type 'System.Web.HttpUnhandledException' was thrown. ---> System.NullReferenceException: Object reference not set to an instance of an object.
at ASP.views_shared_searchcontrol_ascx.__Render__control1(HtmlTextWriter __w, Control parameterContainer)
at System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children)
at System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children)
at System.Web.UI.Page.Render(HtmlTextWriter writer)
at System.Web.Mvc.ViewPage.Render(HtmlTextWriter writer)
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
Another Example (While building sitemap, sitemap code omitted)
System.Web.HttpException: Error executing child request for handler 'System.Web.Mvc.HttpHandlerUtil+ServerExecuteHttpHandlerWrapper'. ---> System.Web.HttpUnhandledException: Exception of type 'System.Web.HttpUnhandledException' was thrown. ---> System.NullReferenceException: Object reference not set to an instance of an object.
at ASP.views_shared_site_master.__Render__control1(HtmlTextWriter __w, Control parameterContainer)
at System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children)
at System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children)
at System.Web.UI.Page.Render(HtmlTextWriter writer)
at System.Web.Mvc.ViewPage.Render(HtmlTextWriter writer)
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
--- End of inner exception stack trace ---
at System.Web.UI.Page.HandleError(Exception e)
I was having this problem. For me it turned out I had strongly typed my master page to be of a certain type and in some scenarios I was returning a model that was not of that type and that is what was causing this error.
Related
I am having an odd issue.
My MVC application seems to be working perfectly fine except for one view page.
The view page in question (Organization/Edit) gets a 'NullReferenceException' on every code item on the page. Whether it is Html.TextBoxFor() or HTML.AntiForgeryToken().
I have my model, view, and controller laid out here on another question that i think is related -- https://stackoverflow.com/questions/26475866/dropdownlistfor-null-reference-error
As you can see below, my model does have information inside of it. This screen capture was taken at the "Return View("Edit", model)" inside the controller.
Exception Details
- Source = App_Web_zu4jlld0
- StackTrace = at ASP._Page_Views_Organization_Edit_vbhtml.Execute() in C:\Users\mtaylor\Projects\Check Im Here\mtaylor-branch\CheckImHere_v2\CheckImHereMVC\Views\Organization\Edit.vbhtml:line 16
at System.Web.WebPages.WebPageBase.ExecutePageHierarchy()
at System.Web.Mvc.WebViewPage.ExecutePageHierarchy()
at System.Web.WebPages.StartPage.RunPage()
at System.Web.WebPages.StartPage.ExecutePageHierarchy()
at System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage)
at System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter writer, Object instance)
at System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter writer)
at System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context)
at System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult)
at System.Web.Mvc.ControllerActionInvoker.<>c__DisplayClass1a.<InvokeActionResultWithFilters>b__17()
at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func`1 continuation)
View
#ModelType CheckImHereMVC.OrganizationEditViewModel
#Using Html.BeginForm("Edit", "Organization", FormMethod.Post)
#Html.AntiForgeryToken() 'get errors here
#Html.ValidationSummary(True) 'get errors here
#Html.TextBoxFor(Function(model) model.organizationSub.subName, New With {.class = "span12"}) 'and errors here
End Using
One thing i notice is that if i comment out my 'textboxfor', my error will occur at the 'ValidationSummary()', if i comment out my 'ValidationSummary()', then my error will occur at 'AntiForgeryToken()'.
So it seems that the error just happens at the last possible code area.
I found the answer to my problem here
For anyone finding this:
Try commenting out the next code line AFTER the error.
#ModelType CheckImHereMVC.OrganizationEditViewModel
#Using Html.BeginForm("Edit", "Organization", FormMethod.Post)
#Html.AntiForgeryToken()
#Html.ValidationSummary(True)
#Html.TextBoxFor(Function(model) model.organizationSub.subName, New With {.class = "span12"})
#Html.TextBoxFor(Function(model) model.organizationSub.subTitle, New With {.class = "span12"})
<img src="#Url.Content(Model.img.imgPath)" alt="IMAGES"/> 'commenting out this line fixed my issue
End Using
In the case above, i would get errors on the model.organizationSub.subTitle. If i commented that line out, i would get errors on the model.organizationSub.subName line. I then found the link mentioned and commented out the line AFTER all of my TextBoxFors. That fixed my issue.
From link: "Some times compiler could not point on exact lines having specific kind of errors in razor view may be because it could not keep their line number in stack trace or somewhere. I have found this case with Null Reference Exception and when null is passed in Url.Content.
So it helps to check the next C# statement in razor view when you did not get any error on the line shown by stack trace."
Here are the symptoms I am experiencing:
I have a brand new empty controller in an area:
public class JamController : Controller
{
public JamController()
{
throw new Exception("Not implemented!");
}
If I visit http://myprojectserver.example.com:12345/urlthatdoesnotexist, I get the following error:
[CompositionException: The composition produced a single composition error. The root cause is provided below. Review the CompositionException.Errors property for more detailed information.
1) Not implemented!
Resulting in: An exception occurred while trying to create an instance of type 'MyWebProject.Areas.Users.Controllers.JamController'.
Resulting in: Cannot activate part 'MyWebProject.Areas.Users.Controllers.JamController'.
Element: MyWebProject.Areas.Users.Controllers.JamController --> MyWebProject.Areas.Users.Controllers.JamController
Resulting in: Cannot get export 'MyWebProject.Areas.Users.Controllers.JamController (ContractName="System.Web.Mvc.IController")' from part 'MyWebProject.Areas.Users.Controllers.JamController'.
Element: MyWebProject.Areas.Users.Controllers.JamController (ContractName="System.Web.Mvc.IController")
]
System.ComponentModel.Composition.Hosting.CompositionServices.GetExportedValueFromComposedPart(ImportEngine engine, ComposablePart part, ExportDefinition definition) +55
System.ComponentModel.Composition.Hosting.CatalogExportProvider.GetExportedValue(CatalogPart part, ExportDefinition export, Boolean isSharedPart) +78
System.ComponentModel.Composition.Hosting.CatalogExport.GetExportedValueCore() +47
System.ComponentModel.Composition.Primitives.Export.get_Value() +57
System.ComponentModel.Composition.ExportServices.GetCastedExportedValue(Export export) +40
System.ComponentModel.Composition.<>c__DisplayClassa`1.<CreateStronglyTypedLazyOfT>b__6() +39
System.Lazy`1.CreateValue() +416
System.Lazy`1.LazyInitValue() +382
System.Lazy`1.get_Value() +75
MefContrib.Web.Mvc.<>c__DisplayClass4.<GetControllerType>b__0(Lazy`1 e) +53
System.Linq.WhereSelectEnumerableIterator`2.MoveNext() +204
System.Collections.Generic.List`1..ctor(IEnumerable`1 collection) +381
System.Linq.Enumerable.ToList(IEnumerable`1 source) +58
MefContrib.Web.Mvc.CompositionControllerFactory.GetControllerType(RequestContext requestContext, String controllerName) +412
System.Web.Mvc.DefaultControllerFactory.System.Web.Mvc.IControllerFactory.GetControllerSessionBehavior(RequestContext requestContext, String controllerName) +61
System.Web.Mvc.MvcRouteHandler.GetSessionStateBehavior(RequestContext requestContext) +122
System.Web.Mvc.MvcRouteHandler.GetHttpHandler(RequestContext requestContext) +33
System.Web.Mvc.MvcRouteHandler.System.Web.Routing.IRouteHandler.GetHttpHandler(RequestContext requestContext) +10
System.Web.Routing.UrlRoutingModule.PostResolveRequestCache(HttpContextBase context) +9709884
System.Web.Routing.UrlRoutingModule.OnApplicationPostResolveRequestCache(Object sender, EventArgs e) +82
System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +136
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +699
My question is "Why?" Why on earth is it trying to instantiate this controller? Where do I look to determine what is causing this. I'm pretty sure it isn't expected behaviour to instantiate every controller on "page not found".
I'm at a loss to know where to look. Can someone point me in the direction of something that will help?
UPDATE:
Turns out that the SetControllerFactory method below is causing the issue:
// Tell MVC3 to use MEF as its dependency resolver.
var dependencyResolver = new CompositionDependencyResolver(catalog);
DependencyResolver.SetResolver(dependencyResolver);
// Tell MVC3 to resolve dependencies in controllers
ControllerBuilder.Current.SetControllerFactory(
new CompositionControllerFactory(
new CompositionControllerActivator(dependencyResolver)));
Commenting out the "Tell MVC3 to resolve dependencies in controllers" section fixes my issue, and no controllers except those I ask for get instantiated. Luckily, that's only needed if you're not using the standard Asp.Net controller resolution (and we are).
This is down to a bug in MefContrib.Web.Mvc. This assembly implements it's own ControllerFactory that inherits from DefaultControllerFactory.
The factory overrides GetControllerType, I assume to try and resolve controllers that live in assemblies somewhere other than the default application or it's references. The implementation of GetControllerType first calls into base.GetControllerType to see if Defaultcontroller can resolve it.
If it can't - which is the case for urls that don't exist - it asks MEF for all exports that implement IController. This returns an IEnumerable<Lazy<IController>> with one item for every class that implements IController in the bin/ folder (by default).
It then runs a linq query over the IEnumerable, calling GetType() on the Value property of each Lazy<IController>. Requesting the Value of a Lazy<T> forces the instance to be created. This is why every controller in the bin/ is being constructed for a page that doesn't exist.
I don't think this is an easy problem to fix properly as there is no way of getting the Type instance from Lazy<T>.Value without creating the value. However by removing the lines from AppStart_MefContribMVC3.cs that register the ControllerFactory with Asp.Net - you have effectively stopped using MefContrib.Web.Mvc's ControllerFactory and just used Asp.Net's DefaultControllerFactory instead.
Turns out that the SetControllerFactory method below is causing the issue:
// Tell MVC3 to use MEF as its dependency resolver.
var dependencyResolver = new CompositionDependencyResolver(catalog);
DependencyResolver.SetResolver(dependencyResolver);
// Tell MVC3 to resolve dependencies in controllers
ControllerBuilder.Current.SetControllerFactory(
new CompositionControllerFactory(
new CompositionControllerActivator(dependencyResolver)));
Commenting out the "Tell MVC3 to resolve dependencies in controllers" section fixes my issue, and no controllers except those I ask for get instantiated. Luckily, that's only needed if you're not using the standard Asp.Net controller resolution (and we are).
I created a basic .NET 4.0 application and referenced the Saxon assemblies. Here is the list of dll's I referenced in the project.
saxon9.dll
saxon9api.dll
IKVM.OpenJDK.ClassLibrary.dll
IKVM.Runtime.dll
The code for the application is as follows:
Sub Main()
Console.WriteLine("Trying to instantiate SaxonProcessor...")
Try
Dim SaxonProcessor As Saxon.Api.Processor = New Saxon.Api.Processor()
Catch ex As Exception
Console.WriteLine("Error: " & ex.Message & ex.StackTrace)
Console.Read()
End Try
Console.WriteLine("Saxon instantiated successfully!")
Console.Read()
End Sub
When I run this application on our IIS machine, I get the following output:
Trying to instantiate SaxonProcessor...
Saxon instantiated successfully!
I then created a basic web application project and referenced the same files as the windows application. I deployed the web application to a virtual directory that contains all the referenced assemblies. I put the following code inside my Default.aspx page:
Public Class _Default
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Response.Write("Trying to instantiate SaxonProcessor...")
Try
Dim SaxonProcessor As Saxon.Api.Processor = New Saxon.Api.Processor()
Response.Write("Saxon instantiated successfully!")
Catch ex As Exception
Response.Write("Error: " & ex.Message & ex.StackTrace)
End Try
End Sub
End Class
When I load the page, it gives me this exception:
Trying to instantiate SaxonProcessor...Error: The type initializer for 'IKVM.NativeCode.java.lang.Thread' threw an exception. at IKVM.NativeCode.java.lang.Class.forName0(String name, Boolean initialize, Object loader) at java.lang.Class.forName0(String , Boolean , ClassLoader ) at java.lang.Class.forName(String className) at net.sf.saxon.dotnet.DotNetExtensionFunctionFactory.class$(String x0) at net.sf.saxon.dotnet.DotNetExtensionFunctionFactory..ctor(Configuration config) at net.sf.saxon.dotnet.DotNetPlatform.initialize(Configuration config) at net.sf.saxon.Configuration.init() at net.sf.saxon.Configuration..ctor() at Saxon.Api.Processor..ctor() at BealSaxxon._Default.Page_Load(Object sender, EventArgs e) in C:\Users\u0147101\Desktop\BealSaxxon\BealSaxxon\Default.aspx.vb:line 9
FULL STACKTRACE FROM IIS MACHINE:
System.TypeInitializationException: The type initializer for 'IKVM.NativeCode.java.lang.Thread' threw an exception. ---> System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.TypeInitializationException: The type initializer for 'java.io.BufferedInputStream' threw an exception. ---> java.lang.RuntimeException: java.lang.IllegalAccessException: Class java.util.concurrent.atomic.AtomicReferenceFieldUpdater can not access a member of class java.io.BufferedInputStream with modifiers "volatile" ---> java.lang.IllegalAccessException: Class java.util.concurrent.atomic.AtomicReferenceFieldUpdater can not access a member of class java.io.BufferedInputStream with modifiers "volatile"
at sun.reflect.misc.ReflectUtil.ensureMemberAccess(Class currentClass, Class memberClass, Object target, Int32 modifiers)
at java.util.concurrent.atomic.AtomicReferenceFieldUpdater.AtomicReferenceFieldUpdaterImpl..ctor(Class , Class , String )
--- End of inner exception stack trace ---
at java.util.concurrent.atomic.AtomicReferenceFieldUpdater.AtomicReferenceFieldUpdaterImpl..ctor(Class , Class , String )
at java.util.concurrent.atomic.AtomicReferenceFieldUpdater.newUpdater(Class tclass, Class vclass, String fieldName)
at java.io.BufferedInputStream..cctor()
--- End of inner exception stack trace ---
at java.io.BufferedInputStream.__<clinit>()
at java.lang.System.initializeSystemClass()
--- End of inner exception stack trace ---
at System.RuntimeMethodHandle._InvokeMethodFast(IRuntimeMethodInfo method, Object target, Object[] arguments, SignatureStruct& sig, MethodAttributes methodAttributes, RuntimeType typeOwner)
at System.RuntimeMethodHandle.InvokeMethodFast(IRuntimeMethodInfo method, Object target, Object[] arguments, Signature sig, MethodAttributes methodAttributes, RuntimeType typeOwner)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters)
at IKVM.NativeCode.java.lang.Thread..cctor()
--- End of inner exception stack trace ---
at IKVM.NativeCode.java.lang.Class.forName0(String name, Boolean initialize, Object loader)
at java.lang.Class.forName(String className)
at net.sf.saxon.dotnet.DotNetExtensionFunctionFactory.class$(String x0)
at net.sf.saxon.dotnet.DotNetExtensionFunctionFactory..ctor(Configuration config)
at net.sf.saxon.dotnet.DotNetPlatform.initialize(Configuration config)
at net.sf.saxon.Configuration.init()
at net.sf.saxon.Configuration..ctor()
at Saxon.Api.Processor..ctor()
at EDG.Transforms..ctor()
at EDG.Main..ctor(NameValueCollection applicationSettings, List`1 exceptionList)
at EDG.EGallery..ctor(NameValueCollection ConfigurationSettings, List`1 ExceptionList)
Has anyone seen this exception before? I've searched extensively on Google but nobody seems to have had this specific exception. I'm thinking it's a permissions problem with IIS, but I don't know for sure. The application pool this application is running under is setup with a machine administrator.
I think this can be 2 types of causes.
One of the IKVM dll is missing. Add all dll of IKVM to test if this solve the problem.
IKVM is compiled for .NET 2 and not version 4. You need to add a version mapping to your app.config.
In this situation, it was a product called OpNET that was interfering with apps using the JVM. Once its services and processes were stopped, the Saxon assembly worked fine.
I created a MVC 2 Application to work as a RSS Feeder and deliver News Contents for a number of applications to consume.
Everything was doing fine until yesterday when suddenly my application started throwing a random error which doesn't tell me much of what's going on (or at least I don't understand it).
This error only occurs in Production and cannot be reproduced in staging or my local machine.
Here's the stack trace:
Error executing child request for handler
'System.Web.Mvc.HttpHandlerUtil+ServerExecuteHttpHandlerWrapper'.errorPath:/Android/Edition/2011-11-22/P1
HostIP:##.##.##.## at
System.Web.HttpServerUtility.ExecuteInternal(IHttpHandler handler,
TextWriter writer, Boolean preserveForm, Boolean setPreviousPage,
VirtualPath path, VirtualPath filePath, String physPath, Exception
error, String queryStringOverride) at
System.Web.HttpServerUtility.Execute(IHttpHandler handler, TextWriter
writer, Boolean preserveForm, Boolean setPreviousPage) at
System.Web.HttpServerUtility.Execute(IHttpHandler handler, TextWriter
writer, Boolean preserveForm) at
System.Web.HttpServerUtilityWrapper.Execute(IHttpHandler handler,
TextWriter writer, Boolean preserveForm) at
System.Web.Mvc.ViewPage.RenderView(ViewContext viewContext) at
System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context)
at System.Web.Mvc.ControllerActionInvoker.<>c_DisplayClass14.b_11()
at
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter
filter, ResultExecutingContext preContext, Func1 continuation) at
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter
filter, ResultExecutingContext preContext, Func1 continuation) at
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext
controllerContext, IList1 filters, ActionResult actionResult) at
System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext
controllerContext, String actionName) at
System.Web.Mvc.Controller.ExecuteCore() at
System.Web.Mvc.MvcHandler.<>c__DisplayClass8.b__4() at
System.Web.Mvc.Async.AsyncResultWrapper.<>c__DisplayClass1.b__0() at
System.Web.Mvc.Async.AsyncResultWrapper.<>c__DisplayClass81.b__7(IAsyncResult
_) at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.End() at
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult)
at
System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step,
Boolean& completedSynchronously)
This error only occurs sometimes and can throw at any action of any controller.
I would like to have found the reason in a specific action but it only throws sometimes and can throw for any action.
Such byzantine errors are hard to debug. The stack trace you're seeing does not help in diagnosing the error.
First, you should improve error logging. In your global.asax, create an implementation of the Application_Error hook that logs the exception and all inner exceptions to a file (I wouldn't log this to the database, because the db connection could be the culprit). Make sure that this code is solid: it should focus on these critical errors and not log every 404 page. Also, make sure that the logging code itself does not create any problems (it should be highly error tolerant).
The cause for this kind of problems is usually access to some kind of static variables. Out of all keywords, I believe static is by far the most dangerous one because it is so subtle.
Some common errors I've seen.
Caching Someone wanted to be smart and cache some data in a static dictionary or so. Unfortunately, the locking code is flawed. An exception occurs only if the code for some user tries to add sth. to the cache, but it's already there:
if(_dict.ContainsKey(cacheKey) == false)
{
// second thread adds data to the dictionary here
_dict.Add(cacheKey, cacheData); // exception
}
This can also happen in a 3rd party library that uses caching or pooling. Access static variables with care.
Uncommon Code Paths Something unusual happens that calls code that is not called very often, and that code is flawed. If you have testing with high code coverage, check the spots that are not covered by the tests.
DB Connection Lost A socket reset on the db connection could lead to exceptions. Many database connection libraries / drivers fix this quickly (i.e. the next request will be fine). This is hard to handle; basically it shouldn't happen but there are many reasons why it could occur.
This error tells you, that the true error is somewhere in some child action, that is action rendered by Html.RenderAction().
There is no such thing as "random" error - there has to be scenario where it happens, you just dont know it because the conditions vary maybe.
You should identify all your child actions, and test them with various inputs.. after you identify the problematic input set, try disabling child actions one by one and find the error this way.
I'm trying to have my ASP.NET MVC2 controllers built using StructureMap but ASP.NET doesn't seem to remember that I've called ControllerBuilder.Current.SetControllerFactory in my Global.asax file.
Specifically I get the error that my controller has no parameterless constructor. The stack trace reveals that my custom ControllerFactory was never actually executed.
Here is my call to the method that should tell ASP.NET which ControllerFactory to use:
Sub Application_Start()
RegisterRoutes(RouteTable.Routes)
ControllerBuilder.Current.SetControllerFactory(GetType(StructureMapControllerFactory))
BootStrapper.RegisterDependencies()
End Sub
And here's the exception that I receive.
[TargetInvocationException: Exception has been thrown by the target of an invocation.]
System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandle& ctor, Boolean& bNeedSecurityCheck) +0
System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean fillCache) +86
System.RuntimeType.CreateInstanceImpl(Boolean publicOnly, Boolean skipVisibilityChecks, Boolean fillCache) +230
System.Activator.CreateInstance(Type type, Boolean nonPublic) +67
System.Web.Mvc.DefaultControllerFactory.GetControllerInstance(RequestContext requestContext, Type controllerType) +80
Why is ASP.NET forgetting which ControllerFactory to use?
How is your StructureMapControllerFactory defined? Does it have a default constructor?
If not, try using that second overload of the SetControllerFactory method:
// First create the controllerFactory instance...
ControllerBuilder.Current.SetControllerFactory(controllerFactory);
You have to set your controllerFactory before you RegisterRoutes...