Linq to Sql与分层

如果想一个项目需要更换数据库时,业务层必须和数据层脱离依赖关系 

表的实体应该是贯穿整个项目的,可是以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 " );
        }
    }

 

  //业务层只需要调用某个数据层(可能是ACCESS,可能是Linq to sql)实现了数据操作接口的类

         private   static  IMessageDataComponent messageDataComponent  =  DataComponentFactory.CreateMessageDataComponent();

 

 

转载于:https://www.cnblogs.com/renjuwht/archive/2010/02/11/1667668.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值