在Asp.net 4.0 中动态注册HttpModule

动态注册HttpModule使我们使用自定义的HttpModel时候不在需在配置文件里配置HttpModel,避免过多的配置出错情况。让我们来看看如何实现动态注册HttpModule.

 

First,我们实现自定义的HttpModel

public class CustomModule : IHttpModule
    {
        
public void Dispose()
        {
            
//nothing to do here
        }

        
public void Init(HttpApplication context)
        {
            context.BeginRequest 
+= (sender, e) => ProcessCookie((HttpApplication)sender);
        }
    }
}
  


Second,建立一个静态类,并命名为PreApplicationStartCode,并增加一个静态方法PreStart()

 

    public class PreApplicationStartCode
    {
        
private static bool _isStarting;

        
public static void PreStart()
        {
            
if (!_isStarting)
            {
                _isStarting 
= true;

                
//注意这里的动态注册,此静态方法在Microsoft.Web.Infrastructure.DynamicModuleHelper
                DynamicModuleUtility.RegisterModule(typeof(CustomModule));
            }
        }
    }

Note.这里的类名官方里面建议用PreApplicationStartCode,我没测试过,大家可以测试下用其他类名

 

Three,在Properties/AssemblyInfo.cs里面注册

[assembly: PreApplicationStartMethod(typeof(MyTest.PreApplicationStartCode), "PreStart")]

 

通过这三步,你的HttpModule就不在需要为每个应用程序去配置了,这种方式比较适合开发组件DLL的时候,需要注册HttpModule的情况,微软的Asp.net MVC3里都是使用的动态HttpModule,有兴趣可以去看源码。

 

posted @ 2011-08-01 18:42  Sphix  阅读(2672)  评论(10编辑  收藏  举报