Loneliness is so beautiful: Discontinuing from application_start, making initialization code more elegant

Source: Internet
Author: User

Here, "loneliness" refers to ASP. NETProgramInitialization inCodeMove from the application_start () method of Global. asax. CS to a separate assembly without any interaction with the assembly of the web project. For example, the Assembly where the initialization code is located is cnblogs. bootstrapper, and the Assembly of the web project is cnblogs. Web. in Visual Studio, there is no reference relationship between the two projects.

Code becomes more beautiful because of low coupling and loneliness. In life, being lonely can keep people quiet and enjoyMoreThe beauty of thinking.

This articleArticleYou can use either of the following methods to make the initialization code more elegant:

1) preapplicationstartmethod (New Features of ASP. NET 4.0, see here ).

2) bootstrapper (codeplex open source project, see http://bootstrapper.codeplex.com /).

Use application_start ()

First, let's take a look at the sample code for initialization directly on application_start () without using bootstrapper:

 Public   Static  Void Registerglobalfilters (globalfiltercollection filters)
{
Filters. Add ( New Handleerrorattribute ());
}

Public Static Void Registerroutes (routecollection routes)
{
Routes. ignoreroute ( " {Resource}. axd/{* pathinfo} " );
Routes. maproute (
" Default " ,
" {Controller}/{action}/{ID} " ,
New {Controller = " Home " , Action = " Index " , Id = urlparameter. optional}
);
}

Protected Void Application_start ()
{
// MVC Registration
Arearegistration. registerallareas ();
Registerglobalfilters (globalfilters. filters );
Registerroutes (routetable. routes );

// IOC container Registration
VaR Container = iocfactory. instance. currentcontainter;
Container. registertype <iblogsiteservice, fakeblogsiteservice> ();
Container. registertype <iblogpostservice, fakeblogpostservice> ();
}

This is a common scenario. Some initialization registration and configuration are completed in application_start (), but the code is always not pleasing to the eye.

After using test-driven development (TDD), it is not only difficult to see, but also not easy to use, because Initialization is also required in the test project, but the test project cannot call application_start () method.

At that time, we moved this part of initialization code to an independent assembly (cnblogs. bootstrapper) because it was required for testing. After the app is released independently, both application_start () and the test project are initialized by calling the cnblogs. bootstrapper. initializer. initialize () method.

In this way, although independent, it is not lonely or beautiful. Because:

1. The web project depends on cnblogs. bootstrapper;

2. the initialization code is still heap in some places.

Solution

For the first question» Use the new preapplicationstartmethod in ASP. NET 4.0. Add the following code to assemblyinfo. CS of the cnblogs. bootstrapper project:

[Assembly: preapplicationstartmethod (Typeof(Cnblogs. bootstrapper. initializer ),"Initialize")]

Note: cnblogs. bootstrapper. initializer is a static class, and the static method in initialize is initializer.

ASP. NET runtime will automatically discover this definition in the Assembly and execute the initialize method specified here before calling application_start.

Note that arearegistration. registerallareas (); can only be executed in application_start (); otherwise, an error is returned:

This method cannot be called during the application's pre-start initialization stage.

For the second question» Use bootstrapper to organize different initialization codes into different tasks (implementing the istartuptask Interface), call these tasks through the fluent API of Bootstrap. bootstrapper, and specify the execution sequence of the tasks. For example, we have two tasks: iocregistertask and registerroutestask. The iocregistertask must be executed first. The code for running these two tasks is as follows:

Public Static ClassInitializer
{
Public Static VoidInitialize ()
{
Bootstrap. bootstrapper. With. startuptasks ()
. Usingthisexecutionorder (S => S. First <registerroutestask> (). Then <iocregistertask> ())
. Start ();
}
}

The implementation code of iocregistertask is as follows:

Public ClassIocregistertask: istartuptask
{
# RegionIstartuptask members

Public VoidRun ()
{
VaRContainer = iocfactory. instance. currentcontainter;
Container. registertype <iblogsiteservice, fakeblogsiteservice> ();
Container. registertype <iblogpostservice, fakeblogpostservice> ();
}

Public VoidReset ()
{
}

# Endregion
}

The registerroutestask implementation code is as follows:

 Public   Class Registerroutestask: istartuptask
{
# Region Istartuptask members

Public Void Run ()
{
Registerglobalfilters (globalfilters. filters );
Registerroutes (routetable. routes );
}

Private Void Registerroutes (routecollection routes)
{
Routes. maproute (
" Default " ,
" {Controller}/{action}/{ID} " ,
New {Controller = " Home " , Action = " Index " , Id = urlparameter. optional}
);
}

Public Void Registerglobalfilters (globalfiltercollection filters)
{
Filters. Add ( New Handleerrorattribute ());
}

Public Void Reset ()
{
}

# Endregion
}

Summary

The beauty of code is the same as that of literature, painting, and music. The process is endless, and the fun is endless. The premise is that you really like it. Some people say that program writing is a meal of youth. This is definitely a wrong idea! Because writers, painters, and musicians do not eat youth meals, so do programmers! Writing it here, I suddenly thought that when I was old, it would be interesting to take out the code I wrote when I was young and refactor it!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.