___________UPDATE____________
Approached from a different angle to solve the problem with a custom ControllerFactory, see answer below.
________ORIGINAL QUESTION________
I have an MVC codebase used for multiple branded deployments. To meet the demands of each client, we have set up overridable controllers and views.
Route Registrations looks like this
protected void Application_Start()
{
string deploymentName = GetDeploymentName();
RouteConfig.RegisterRoutes(RouteTable.Routes, deploymentName);
}
Within RegisterRoutes we are first looking for matching controllers in the deployment namespace, and if not found, be look in the base namespace.
This works fine if we have a seperate IIS application set up for each deployment, because then each deployment executes its own Application_Start()
However, we are trying to run all the deployments in one IIS site intsance. Which means Application_Start() only gets called once, registering routes only for the 1st deployment to get hit.
I'm trying to move RegisterRoutes out of Application_Start() to something like Session_Start() or Application_PreRequestHandlerExecute()
protected void Application_PreRequestHandlerExecute()
{
string deploymentName = GetDeploymentName();
using (RouteTable.Routes.GetWriteLock())
{
RouteTable.Routes.Clear();
RouteConfig.RegisterRoutes(RouteTable.Routes, deploymentName);
}
}
With this code, each request gets the current deployment namespace, clears the routetable, and registers the routes again using the new namespace.
2 problems:
1: the request still executes based on whatever the PREVIOUS routes were. So I'm in the wrong part of the lifecycle because the request at this point is already destined for a specific controller and action.
2: the next request will throw an exception:
Exception Details: System.InvalidOperationException: Multiple types were found that match the controller named 'Home'. This can happen if the route that services this request ('{controller}/{action}/{id}') does not specify namespaces to search for a controller that matches the request. If this is the case, register this route by calling an overload of the 'MapRoute' method that takes a 'namespaces' parameter.
Even though I've unregistered the previous routes, the application still seems to be hanging on to the previously registered controller, and now that I've registered another route to another controller of the same name, there is ambiguity between the two controllers.
My 2 main questions are:
1. Is there any other lifecycle event other than Application_Start() that I can use to register new routes before the request is already resolved to a previously existing route?
2. How can I completely clear the routes and controllers so that I don't get ambiguity exceptions with the previously registered controllers?