Before reading this article, I recommend reading the previous par.:
In this section, we are going to delve further into the MVC Life Cycle. In the previous section, we saw the basic flow of MVC. However, let us consider the case wherein you need to inject your custom module and want to do logging extensively. In this kind of situation you want to execute some custom codes before the application actually starts. In order to achieve this kind of scenario, you need to make use of PreApplicationStartMethod @ assembly level. The following is the actual line of code for registering your custom module at PreApplicationStartMethod level.
[assembly: PreApplicationStartMethod (typeof(MvcApplication), "RegisterCustomModule")] . But, before this let me show the snippet for the custom module which I have created here.
- using System.Diagnostics;
- using System.Web;
- namespace MVC_Life_Cycle.CustomModules
- {
- public class CustomModule: IHttpModule
- {
- public void Init(HttpApplication context)
- {
- context.LogRequest += Context_LogRequest;
- }
- private void Context_LogRequest(object sender, System.EventArgs e)
- {
- Debug.WriteLine("Item Logged Successfully");
- }
- public void Dispose()
- {
- throw new System.NotImplementedException();
- }
- }
- }
This is the simple snippet wher in I am actually implementing "
IHttpModule." This is a straight forward snippet. Here, at every HTTP Event it will just print the message "
Item Logged Successfully." Also, I have modified the global.asax file as well. The following is the snippet for the same.
- using System.Diagnostics;
- using System.Web;
- using System.Web.Mvc;
- using System.Web.Optimization;
- using System.Web.Routing;
- using MVC_Life_Cycle;
- using MVC_Life_Cycle.CustomModules;
- [assembly: PreApplicationStartMethod(typeof(MvcApplication), "RegisterCustomModule")]
- namespace MVC_Life_Cycle
- {
- public class MvcApplication: System.Web.HttpApplication
- {
- public static void RegisterCustomModule()
- {
- HttpApplication.RegisterModule(typeof(CustomModule));
- }
- protected void Application_Start()
- {
- AreaRegistration.RegisterAllAreas();
- FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
- RouteConfig.RegisterRoutes(RouteTable.Routes);
- BundleConfig.RegisterBundles(BundleTable.Bundles);
- }
- protected void Application_End()
- {
- Debug.WriteLine("Application Stopped");
- }
- }
- }
With the above change in place, when I run the app, then it will produce the following results:
Then, Application_Start event will get triggered.
At this stage, our custom module which we created would have gottenregistered with our other existing modules as shown below.
Now, when I inspect the output window, it will produce the following result:
Since this is
HTTPModule, it will print the message number of the times
HTTP-Request happens. Here, we can see that message got printed successfully. I hope you have liked this post. In the coming section, we will delve further.
Code Download