现在的位置: 首页 > 综合 > 正文

ibatis.net的配置文件设计

2013年07月25日 ⁄ 综合 ⁄ 共 2310字 ⁄ 字号 评论关闭
刚开始用ibatis.net的时候,所有的文章都是把配置文件放在了web.config同级目录下,我也就以为这是默认的,没办法修改。
但是随着项目的进行,Config的增多导致必须把ibatis的配置文件统一管理并加入加密的功能,于是又仔细的看了下ibatis的文档和源代码。
看了源代码后清晰了很多,原来高明的作者早就留了接口给我们扩展。佩服一下,比偶强太多了啊。
由于在这个项目中,又在ibatis.net 上面包装了一层,DPSSqlMapper()就是SqlMapper的一个扩展。
1。在DPSSqlMapper()的构造器函数里面,可以如下操作:
 public DPSSqlMapper()
        {
            // Get default mapper
            ConfigureHandler handler = new ConfigureHandler(Configure);
            DomSqlMapBuilder builder = new DomSqlMapBuilder();
            _isqlMapper = builder.ConfigureAndWatch(DPSSqlMapperConst.DEFAULT_SQLMAP_CONFIG_PATH , handler);   
        }
        // filepath locates
        public DPSSqlMapper(string filepath)
        {
            // Get mapper according to map config name
            ConfigureHandler handler = new ConfigureHandler(Configure);
            DomSqlMapBuilder builder = new DomSqlMapBuilder();
            _isqlMapper = builder.ConfigureAndWatch(filepath, handler);
        }
 
// 重设config
 protected  void Configure(object obj)
        {
            _isqlMapper = null;//(SqlMapper) obj;
        }
2。DPSSqlMapperManager负责分配mapper实例,就是工厂的作用
public class DPSSqlMapperManager
    {
             // Use static hashtable to save muti mapper
        private static Hashtable _sqlMapperTable = Hashtable.Synchronized(new Hashtable());
     
        /// <summary>
        /// Return a mapper according to sqlmap config name
        /// </summary>
        /// <returns>An instance of ORM class</returns>
        public  static IDPSSqlMapper CreateMapper(string file)
        {
            if (!_sqlMapperTable.Contains(file))
            {     
                // Create a new mapper
                _sqlMapperTable = DPSSqlMapperImpl.CreateMapper(file);              
            }
            // Get exist mapper from mapper poll
            return (IDPSSqlMapper)_sqlMapperTable;
        }
        /// <summary>
        /// Return a mapper according to sqlmap.config file
        /// </summary>
        /// <returns>An instance of ORM class</returns>
        public static IDPSSqlMapper CreateMapper()
        {
            return CreateMapper(DPSSqlMapperConst.DEFAULT_SQLMAP_CONFIG_PATH); 
        }
              
    }

3。DPSSqlMapperImpl 中用singleton patten 实例化新的mapper
4。如果想要加密connection,可以自己写算法,在构造函数里面实现。当然,为了维护方便,还要写个小工具解密(需要的话)

PS:用static的好处就是快,但是测试的时候遇到过一个问题。就是在debug的时候出现异常后,终止立刻重新执行的话,有时候会出现空引用。就是说在static hashtable会找到,但是这个对象已经被销毁了。我觉得应该是因为debug的时候static是声明在appdomain上,ide重新执行的时候,有时候没有释放,所以才出现上述问题,真实系统应该不会出现这个问题,不知道这样理解对不对。

抱歉!评论已关闭.