Add namespaces with Razor

When you are using ASP.NET with WebFormViewEngine and wants to call a method in a separate namespace, you can add a reference to the namespace in web.config to get a cleaner view.

You can easily do it with:

<add namespace="Custom.Namespace" />

In ASP.NET MVC 3 there is a new View Engine, Razor. If we use this, the code above won’t work since the imports in web.config are ignored.

You can get access to the classes and methods quick and easy by using the “using” statement in the view:

@using Custom.Namespace

We need this in all the views where we want to access the classes, which requires more code.

To get rid of this, we need to know how Razor works. Every time a website with Razor is started, the InlinePageBuildProvider is registered for all files with the .cshtml and .vbhtml extensions. This BuildProvider implementation is used by Razor to build the views. What we need to do here is to add “Custom.Namespace” to the BuildProvider so it can include that when building the views.

What we need to do that is a new class which we can call PreApplicationStart. It has a static method where we add the global import which will be used by InlinePageBuildProvider:

using Microsoft.WebPages.Compilation;
 
public class PreApplicationStart
{
    public static void InitializeApplication()
    {
        CodeGeneratorSettings.AddGlobalImport("Custom.Namespace");
    }
}

To execute this method, we are going to use a new attribute in .NET 4.0, System.Web.PreApplicationStartMethodAttribute. This attribute can only be used by assemblies, so we add the following code in AssemblyInfo.cs:

[assembly: PreApplicationStartMethod(typeof(PreApplicationStart), "InitializeApplication")]

The parameters we send to the attribut is the type of the class where we have the static method, and the name of the static method.

When we start our website, the method will be executed before Application_Start in global.asax, which will make sure we always have access to this namespace in our application.

We can now get access to all classes in Custom.Namespace in our Razor views, just like we could before with WebFormViewEngine.

No Comments