首先建立一个类 为Product 如下:
namespace PetShop.SQLServerDAL {
public class Product : IProduct {
//Static constants
}
注意上述的命名空间是PetShop.SQLServerDAL 类名为Product
这里的命名空间要在配职文件中用到的.
如下:
<appSettings>
<add key="WebDAL" value="PetShop.SQLServerDAL"/>
</appSettings>
然后在新的类中如何根据配职文件关联到上述的Product类呢
在DALFactory 中 用如下代码即可
namespace PetShop.DALFactory {
public sealed class DataAccess {
//去读Appconfig下的WebDAL 得到的是value=PetShop.SQLServerDAL;
private static readonly string path = ConfigurationManager.AppSettings["WebDAL"];
private static readonly string orderPath = ConfigurationManager.AppSettings["OrdersDAL"];
//够造函数
private DataAccess() { }
//利用反射获取类对象去找PetShop.SQLServerDAL下的Product类
public static PetShop.IDAL.IProduct CreateProduct() {
string className = path + ".Product";
return (PetShop.IDAL.IProduct)Assembly.Load(path).CreateInstance(className);
}
}
}
上述有几点要注意:
1:命名空间和配之文件的一致性,类名和利用反射中使用的类名的一致性
2:利用工厂方法根据配只文件去找相应的类,便于维护,
下面讲下PetShop.SQLServerDAL
该命名空间下包含的是和SQL数据操作相关的增删改
namespace PetShop.SQLServerDAL {
//继承自IProduct接口实现该接口下的所有方法
public class Product : IProduct {
//一些常量定义 如SQL语句,传入的参数等等
private const string SQL_SELECT_PRODUCTS_BY_CATEGORY = "SELECT Product.ProductId, Product.Name, Product.Descn, Product.Image, Product.CategoryId FROM Product WHERE Product.CategoryId = @Category";
private const string SQL_SELECT_PRODUCTS_BY_SEARCH3 = ") OR (";
private const string SQL_SELECT_PRODUCTS_BY_SEARCH4 = "))";
private const string SQL_SELECT_PRODUCT = "SELECT Product.ProductId, Product.Name, Product.Descn, Product.Image, Product.CategoryId FROM Product WHERE Product.ProductId = @ProductId";
private const string PARM_CATEGORY = "@Category";
private const string PARM_KEYWORD = "@Keyword";
private const string PARM_PRODUCTID = "@ProductId";
/// <summary>
/// Query for products by category
/// </summary>
/// <param name="category">category name</param>
/// <returns>A Generic List of ProductInfo</returns>
public IList<ProductInfo> GetProductsByCategory(string category) {
IList<ProductInfo> productsByCategory = new List<ProductInfo>();
SqlParameter parm = new SqlParameter(PARM_CATEGORY, SqlDbType.VarChar, 10);
parm.Value = category;
//Execute a query to read the products
//注意using 语句的使用
using (SqlDataReader rdr = SqlHelper.ExecuteReader(SqlHelper.ConnectionStringLocalTransaction, CommandType.Text, SQL_SELECT_PRODUCTS_BY_CATEGORY, parm)) {
while (rdr.Read()) {
ProductInfo product = new ProductInfo(rdr.GetString(0), rdr.GetString(1), rdr.GetString(2), rdr.GetString(3), rdr.GetString(4));
productsByCategory.Add(product);
}
}
return productsByCategory;
}