Initialize assemblies using PreApplicationStartMethod for ASP.NET 4.0 Application

Sometimes your ASP.NET application needs to hook up some code before even the Application is started. Assemblies supports a custom attribute called PreApplicationStartMethod which can be applied to any assembly that should be loaded to your ASP.NET application, and the ASP.NET engine will call the method you specify within it before actually running any of code defined in the application.

Lets discuss how to use it using Steps :

1. Add an assembly to an application and add this custom attribute to the AssemblyInfo.cs. Remember, the method you speicify for initialize should be public static void method without any argument. Lets define a method Initialize. You need to write :

[assembly:PreApplicationStartMethod(typeof(MyInitializer.InitializeType), "InitializeApp")]

2. After you define this to an assembly you need to add some code inside InitializeType.InitializeApp method within the assembly.

public static class InitializeType
{
public static void InitializeApp()
{
// Initialize application
}
}

3. You must reference this class library so that when the application starts and ASP.NET starts loading the dependent assemblies, it will call the method InitializeApp automatically.

Warning

Even though you can use this attribute easily, you should be aware that you can define these kind of method in all of your assemblies that you reference, but there is no guarantee in what order each of the method to be called. Hence it is recommended to define this method to be isolated and without side effect of other dependent assemblies.

The method InitializeApp will be called way before the Application_start event or even before the App_code is compiled.

This attribute is mainly used to write code for registering assemblies or build providers.

Read Documentation

I hope this post would come helpful.

Have fun.

Abhishek Sur

Abhishek Sur is a Microsoft MVP since year 2011. He is an architect in the .NET platform. He has profound theoretical insight and years of hands on experience in different .NET products and languages. He leads the Microsoft User Group in Kolkata named KolkataGeeks, and regularly organizes events and seminars in various places for spreading .NET awareness. He is associated with the Microsoft Insider list on WPF and C#, and is in constant touch with product group teams. He blogs at http://www.abhisheksur.com His Book : Visual Studio 2012 and .NET 4.5 Expert Development Cookbook. Follow Abhishek at Twitter : @abhi2434