如果想一个项目需要更换数据库时,业务层必须和数据层脱离依赖关系
表的实体应该是贯穿整个项目的,可是以Linq to Sql作为DAL,实体就和数据层连一起了
今天看到园子里一位前辈的源代码,他自己写了一个实体,和 Linq to Sql做互换操作。
业务层只需要依赖自己写的实体,就实现了和 Linq to Sql 脱离依赖关系
具体实现多数据库的代码如下
///
<summary>
/// 数据访问组件的工厂类
/// 采用Abstract Factory模式 + 反射机制 + 缓存机制实现
/// </summary>
public class DataComponentFactory
{
// 用哪个数据库从位置文件读
private static readonly string DATA_COMPONENT_LIB = ConfigurationManager.AppSettings[ " DataComponentLib " ];
private static object CreateObject( string className)
{
/// <summary>
/// 取得数据访问组件对象,首先检查缓存,不存在则利用反射机制加载
/// 缓存依赖项为Web.Config文件
/// </summary>
string fullClassName = DATA_COMPONENT_LIB + " . " + className;
object dataComponent = CacheAccessor < object > .GetFromCache(className);
if (dataComponent == null )
{
// CacheDependency fileDependency = new CacheDependency(HttpContext.Current.Server.MapPath("Web.Config"));
dataComponent = Assembly.Load(DATA_COMPONENT_LIB).CreateInstance(fullClassName);
// CacheAccessor<object>.SaveToCache(className, dataComponent, fileDependency);
CacheAccessor < object > .SaveToCache(className, dataComponent);
}
return dataComponent;
}
/// <summary>
/// 生产“留言”的数据访问组件
/// </summary>
/// <returns> “留言”的数据访问组件 </returns>
public static IMessageDataComponent CreateMessageDataComponent()
{
return (IMessageDataComponent)CreateObject( " MessageDataComponent " );
}
}
/// 数据访问组件的工厂类
/// 采用Abstract Factory模式 + 反射机制 + 缓存机制实现
/// </summary>
public class DataComponentFactory
{
// 用哪个数据库从位置文件读
private static readonly string DATA_COMPONENT_LIB = ConfigurationManager.AppSettings[ " DataComponentLib " ];
private static object CreateObject( string className)
{
/// <summary>
/// 取得数据访问组件对象,首先检查缓存,不存在则利用反射机制加载
/// 缓存依赖项为Web.Config文件
/// </summary>
string fullClassName = DATA_COMPONENT_LIB + " . " + className;
object dataComponent = CacheAccessor < object > .GetFromCache(className);
if (dataComponent == null )
{
// CacheDependency fileDependency = new CacheDependency(HttpContext.Current.Server.MapPath("Web.Config"));
dataComponent = Assembly.Load(DATA_COMPONENT_LIB).CreateInstance(fullClassName);
// CacheAccessor<object>.SaveToCache(className, dataComponent, fileDependency);
CacheAccessor < object > .SaveToCache(className, dataComponent);
}
return dataComponent;
}
/// <summary>
/// 生产“留言”的数据访问组件
/// </summary>
/// <returns> “留言”的数据访问组件 </returns>
public static IMessageDataComponent CreateMessageDataComponent()
{
return (IMessageDataComponent)CreateObject( " MessageDataComponent " );
}
}
//业务层只需要调用某个数据层(可能是ACCESS,可能是Linq to sql)实现了数据操作接口的类
private
static
IMessageDataComponent messageDataComponent
=
DataComponentFactory.CreateMessageDataComponent();