实现自动抛弃当前数据库上下文的模块。支持各种ORM框架并存
一:OrmContextAutoDisposeModule.cs
EventHandler PostRequestHandlerExecute
MSDN:在 ASP.NET 事件处理程序(例如,某页或某个 XML Web service)执行完毕时发生。
也就是说注册这个事件的方法可以做一些页面执行完毕的清理工作。如果页面中引入了某个DBContext或者是DataContext,一般情况下这些数据库资源是需要释放的,好处很多就不多少了。注册这个事件,可以在页面执行完毕时统一进行一些清理的工作。因此程序员在编程的时候也没有必要做一些using的资源释放的活了。
namespace MyCompanyName.WebHelpers
{
///<summary>/// 实现自动抛弃当前数据库上下文的模块。
///</summary>publicsealedclass OrmContextAutoDisposeModule : IHttpModule
{
#region IHttpModule 成员
public void Init(HttpApplication context)
{
context.PostRequestHandlerExecute += new EventHandler(Enter);
}
public void Dispose()
{
}
#endregion
private void Enter(object sender, EventArgs e)
{
IDictionary httpContextItems = HttpContext.Current.Items;
// 获取DBContext 或 DataContext 或 ObjectContext
List<object> keys = new List<object>(httpContextItems.Count);
foreach (DictionaryEntry item in httpContextItems)
{
if (item.Value is DataContext || item.Value is ObjectContext || item.Value is DbContext)
{
((IDisposable)item.Value).Dispose();
keys.Add(item.Key);
}
}
foreach (object key in keys)
{
httpContextItems.Remove(key);
}
}
}
}
二.在Web.config文件中注册Module
<add name="OrmContextAutoDisposeModule" type="MyCompanyName.WebHelpers.OrmContextAutoDisposeModule, MyCompanyName.WebHelpers"/>
</httpModules>
三:OrmContextFactory.cs
{
public static TDataContext GetDataContext<TDataContext>()
where TDataContext : DataContext, new()
{
HttpContext httpContext = HttpContext.Current;
if (httpContext != null)
{
string key = typeof(TDataContext).FullName;
TDataContext dataContext = httpContext.Items[key] as TDataContext;
if (dataContext == null)
{
dataContext = new TDataContext();
httpContext.Items[key] = dataContext;
}
return dataContext;
}
return new TDataContext();
}
public static TObjectContext GetObjectContext<TObjectContext>()
where TObjectContext : ObjectContext, new()
{
HttpContext httpContext = HttpContext.Current;
if (httpContext != null)
{
string key = typeof(TObjectContext).FullName;
TObjectContext objectContext = httpContext.Items[key] as TObjectContext;
if (objectContext == null)
{
objectContext = new TObjectContext();
httpContext.Items[key] = objectContext;
}
return objectContext;
}
return new TObjectContext();
}
public static TDbContext GetDbContext<TDbContext>()
where TDbContext : DbContext, new()
{
HttpContext httpContext = HttpContext.Current;
if (httpContext != null)
{
string key = typeof(TDbContext).FullName;
TDbContext dbContext = httpContext.Items[key] as TDbContext;
if (dbContext == null)
{
dbContext = new TDbContext();
httpContext.Items[key] = dbContext;
}
return dbContext;
}
return new TDbContext();
}
}