咱們一般在IBatisNet配置文件 properties.config 加入數據庫鏈接字符串。數據庫鏈接字符串直接放在裏面,沒有被加密,很不安全。若是咱們把 properties.config 文件做爲資源嵌入到程序集,彷佛可用解決安全問題,可是又出現新的問題,那就是部署。由於用戶部署時,是須要從新設置數據庫地址,名稱,用戶名,密碼等值 的。html
解決辦法:
數據庫鏈接字符串仍是放在原來的程序的配置文件中,好比 WebForms 的web.config中, WinForms的 App.config中,這樣咱們能夠以使用企業庫管理工具來加密這個配置文件。web
而後,經過編程的方式加入數據庫鏈接字符串。 sql
因爲咱們本身經過編程的方式提供了 ISqlMapper ,因此咱們須要考慮性能的問題.SqlMap是線程安全的,因此咱們能夠考慮使用單件模式來提供 ISqlMapper .
整個提供 ISqlMapper 的類以下:數據庫
//-----------------------------------------------------------------------------------------
// 模塊編號:
// 文件名: SqlMapperHelper.cs
// 描述: SqlMapperHelper 類
// 做者:ChenJie
// 編寫日期:2007-5-26
// Copyright 2007
//-----------------------------------------------------------------------------------------
using System;
using IBatisNet.DataMapper;
using IBatisNet.DataMapper.Configuration;
using System.Collections.Specialized;
namespace Novelty.CustomSystem.IBatisNet
{
/// <summary>
/// 提供 ISqlMapper 對象,屬於單件模式(Singleton Pattern)
/// </summary>
public class SqlMapperHelper
{
#region 私有變量
/// <summary>
/// ISqlMapper 實例
/// </summary>
private ISqlMapper _sqlMapper;
#endregion
#region 構造函數
/// <summary>
/// 構造函數
/// </summary>
SqlMapperHelper()
{
CreateSqlMapper();
}
#endregion
#region 嵌套類
class Nested
{
static Nested()
{
}
internal static readonly SqlMapperHelper instance = new SqlMapperHelper();
}
#endregion
#region 屬性
/// <summary>
/// 惟一實例
/// </summary>
public static SqlMapperHelper Instance
{
get
{
return Nested.instance;
}
}
#endregion
#region 公有方法
/// <summary>
/// 刷新 ISqlMapper 對象
/// 緣由:當數據庫鏈接出現變化,須要刷新該對象
/// </summary>
public void RefreshSqlMapper()
{
CreateSqlMapper();
}
#endregion
#region 私有方法
/// <summary>
/// 建立 ISqlMapper 對象
/// </summary>
private void CreateSqlMapper()
{
//-----(1)
//DomSqlMapBuilder builder = new DomSqlMapBuilder();
//ISqlMapper _sqlMapper = builder.Configure("SqlMap.config");
//-----(2)
//SqlMap是線程安全的
//Mapper.Get()方法和Mapper.Instance()方法調用默認的 SqlMap.config 配置文件來建立SqlMapper
//ISqlMapper sm = Mapper.Get();
//如下注釋內容摘自一個網友的blog:www.cnblogs.com/shanyou/articles/388602.html 。
//與使用DomSqlMapBuilder類的區別是,Mapper.Get()不須要指定配置文件的名稱,而且使用Mapper.Get()返回SqlMapper後若是映射的XML沒有錯誤的話,會將該XML文件緩存到內存,
//下次調用的時候就不須要在檢查XML文件,直到SqlMap.config被改變,這樣將大大的提升了程序的性能,而使用DomSqlMapBuilder創建的SqlMapper每次都要先分析映射的XML文件,性能將大大的下降
DomSqlMapBuilder builder = new DomSqlMapBuilder();
NameValueCollection prop = new NameValueCollection();
prop.Add("connectionString", DatabaseHelper.GetConnectionString());
builder.Properties = prop;
_sqlMapper = builder.Configure();
}
#endregion
#region 對外屬性
/// <summary>
/// ISqlMapper 實例
/// </summary>
public ISqlMapper SqlMapper
{
get
{
return _sqlMapper;
}
}
#endregion
}
}
編程