Thursday, January 07, 2010

ASP.NET MVC Routing: Global.asax & Single Responsibility Principle




Okay, so let’s continue talking about ASP.NET MVC routing. Basically I wanted to talk about extracting the C# code from my global.asax in the UI project and putting it in my Core project. I also want to talk about removing the routing code from the global.asax.cs. We need to stick with the Single Responsibility Principle. You can see a basic approach to routing in this post.

Step 1: Copy everything between the namespace {} from the global.asax.cs and create a new class (I call mine Global) in your Core project and paste the code into it. You’ll probably need to add a reference to System.Web & System.Web.Mvc.

Step 2: Delete the global.asax.cs. Be sure not to delete the whole global.asax, you only want to delete the global.asax.cs.

Step 3: Open global.asax and delete the Codebehind="Global.asax.cs" and modify the inherits to inherit from your new class (Global.cs). Like this:

<%@ Application Inherits="Core.UI.Global" Language="C#" %>

Okay, now your global.asax doesn’t depend on any C# code in your UI project. This is a good thing!


Step 4: Let’s extract your routes from the new Global.cs and put them into a new class (I call mine RouteConfigurator). By the way, the naming and route extraction is in the ASP.NET MVC in Action sample code. To do so, follow these steps:



  1. Cut everything in the RegisterRoutes() method in the new Global.cs class and paste it into your new RouteConfigurator class so it will now look like this:
    public class RouteConfigurator
{
public virtual void RegisterRoutes()
{
var routes = RouteTable.Routes;
routes.IgnoreRoute(
"{resource}.axd/{*pathInfo}");

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

Notice I added a var routes = RouteTable.Routes; to the top of this method.



  1. Okay, so now we need to tie these things together and we just need to put one line of code in the Global.cs and that will look like this:
        protected void Application_Start()
{
new RouteConfigurator().RegisterRoutes();
//StructureMap Configuration Here
//AutoMapper Configuration Here
//etc
}

So now when Application_Start is called, it will call our RegisterRoutes in our extracted code.


Step 5: Enjoy having single responsibility classes and NO CODE in your UI!


As always, please comment if I can improve or you have questions and thanks for reading!

kick it on DotNetKicks.com

blog comments powered by Disqus
Related Posts Plugin for WordPress, Blogger...