/// <summary> /// 获取一个DbContext对象 /// </summary> /// <param name="name">连接名称</param> /// <param name="autoClose">是否自动关闭</param> /// <returns>DbContext对象</returns> public static DbContext GetContext(string name, bool autoClose) { //得到映射后连接名称 name = DbConnectionMappingContext.GetMappedConnectionName(name); DbProviderFactory factory = DbConnectionManager.GetDbProviderFactory(name); DbConnectionStringBuilder csb = factory.CreateConnectionStringBuilder(); csb.ConnectionString = DbConnectionManager.GetConnectionString(name); bool enlist = true; if (csb.ContainsKey("enlist")) { enlist = (bool)csb["enlist"]; } DbContext result = null; if (enlist) { result = new AutoEnlistDbContext(name, autoClose); } else { result = new NotEnlistDbContext(name, autoClose); } result.autoClose = autoClose; return(result); }
/// <summary> /// 释放对应关系 /// </summary> public void Dispose() { DbConnectionMappingContext context = null; if (DbConnectionMappingContextCache.Instance.TryGetValue(this.sourceConnectionName, out context)) { DbConnectionMappingContextCache.Instance.Remove(this.sourceConnectionName); } }
/// <summary> /// 得到映射后的连接名称 /// </summary> /// <param name="srcConnectionName"></param> /// <returns></returns> public static string GetMappedConnectionName(string srcConnectionName) { DbConnectionMappingContext context = null; string result = srcConnectionName; if (DbConnectionMappingContextCache.Instance.TryGetValue(srcConnectionName, out context)) { result = context.destinationConnectionName; } return(result); }
/// <summary> /// 创建连接名称的对应关系 /// </summary> /// <param name="srcConnectionName"></param> /// <param name="destConnectionName"></param> /// <returns></returns> public static DbConnectionMappingContext CreateMapping(string srcConnectionName, string destConnectionName) { ExceptionHelper.CheckStringIsNullOrEmpty(srcConnectionName, "srcConnectionName"); ExceptionHelper.CheckStringIsNullOrEmpty(destConnectionName, "destConnectionName"); ExceptionHelper.TrueThrow(DbConnectionMappingContextCache.Instance.ContainsKey(srcConnectionName), "已经为连接名称{0}建立了映射关系", srcConnectionName); DbConnectionMappingContext context = new DbConnectionMappingContext(); context.sourceConnectionName = srcConnectionName; context.destinationConnectionName = destConnectionName; DbConnectionMappingContextCache.Instance.Add(context.sourceConnectionName, context); return(context); }