namespace Data
{
/// <summary>
/// 数据库建立工厂
/// Created By : 张占岭
/// Created Date:2011-10-14
/// Modify By:
/// Modify Date:
/// Modify Reason:
/// </summary>
internal static class DbFactory
{
static System.Timers.Timer sysTimer = new System.Timers.Timer(10000);
volatile static Dictionary<Thread, DataContext[]> divDataContext = new Dictionary<Thread, DataContext[]>();
static DbFactory()
{
sysTimer.AutoReset = true;
sysTimer.Enabled = true;
sysTimer.Elapsed += new System.Timers.ElapsedEventHandler(sysTimer_Elapsed);
sysTimer.Start();
}
static void sysTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
List<Thread> list = new List<Thread>();
foreach (Thread item in divDataContext.Keys)
{
if (item.ThreadState == ThreadState.Stopped)
{
list.Add(item);
}
}
for (int index = 0; index < list.Count; index++)
{
for (int refer = 0; refer < divDataContext[list[index]].Length; refer++)
{
if (divDataContext[list[index]][refer] != null)
{
divDataContext[list[index]][refer].Dispose();
divDataContext[list[index]][refer] = null;
}
}
divDataContext.Remove(list[index]);
list[index] = null;
}
list = null;
}
/// <summary>
/// 通过工厂的制造模式获取相应的LINQ数据库连接对象
/// </summary>
/// <param name="dbName">数据库名称(需要与真实数据库名称保持一致)</param>
/// <returns>LINQ数据库连接对象</returns>
public static DataContext Intance(string dbName)
{
return Intance(dbName, Thread.CurrentThread);
}
/// <summary>
/// 通过工厂的制造模式获取相应的LINQ数据库连接对象
/// </summary>
/// <param name="dbName">数据库名称(需要与真实数据库名称保持一致)</param>
/// <param name="thread">当前线程引用的对象</param>
/// <returns>LINQ数据库连接对象</returns>
public static DataContext Intance(string dbName, Thread thread)
{
if (!divDataContext.Keys.Contains(thread))
{
divDataContext.Add(thread, new DataContext[2]);
}
if (dbName.Equals("TEST"))
{
if (divDataContext[thread][0] == null)
{
divDataContext[thread][0] = new Entity.TEST.LinqTESTDataContext();
}
return divDataContext[thread][0];
}
if (dbName.Equals("EEE114"))
{
if (divDataContext[thread][1] == null)
{
divDataContext[thread][1] = new Entity.EEE114.LinqEEE114DataContext();
}
return divDataContext[thread][1];
}
else
{
return null;
}
}
}
}
本文转自博客园张占岭(仓储大叔)的博客,原文链接:MVC+LINQToSQL的Repository模式之(一)数据工厂,如需转载请自行联系原博主。