1.创建项目结构,如下:
引用关系如下(此图来源网络):
2.IService创建接口,如下(用户类接口):
using Model;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace IService
{
/// <summary>
/// 用户数据访问接口
/// </summary>
public interface IUserService
{
/// <summary>
/// 获取所有的用户
/// </summary>
/// <returns>用户DataTable</returns>
DataTable GetAllUser();
/// <summary>
/// 添加用户
/// </summary>
/// <param name="UserVo">用户</param>
/// <returns>受影响的行数</returns>
int AddUser(UserVo user);
}
}
3.在SqlService和OracleService实现IService接口,如下(SqlService用户实现类):
using IService;
using Model;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SQLServerService
{
public class SqlUserService : IUserService
{
/// <summary>
/// 根据用户名ID,删除用户
/// </summary>
/// <param name="id">用户ID</param>
/// <returns>受影响的行数</returns>
public int DeleteUserByName(string id)
{
StringBuilder sqlSB = new StringBuilder();
sqlSB.Append("delete from HT_OIL_USER where id=@id");
SqlParameter[] pa ={
SqlHelper.GetParameter("@id", DbType.String, id)
};
return SqlHelper.ExecuteSql(sqlSB.ToString(), pa);
}
/// <summary>
/// 获取所有的用户
/// </summary>
/// <returns></returns>
public DataTable GetAllUser()
{
StringBuilder sqlSB = new StringBuilder();
sqlSB.Append("select id,USERNAME,PASSWORD from HT_OIL_USER");
sqlSB.Append(" Order by AddTime asc");
return SqlHelper.ExecuteDt(sqlSB.ToString());
}
}
}
4.Manager中,创建工厂类,根据配置的数据库标识,实例化不同的Service对象
using IService;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace Manager
{
public class DalFactory
{
private static readonly string AssemblyName = "OracleService";
// private static readonly string db = "Oracle";
private static readonly string db = ConfigurationManager.AppSettings["DB"].ToLower();
/// <summary>
/// 实例化IUserService对象
/// </summary>
/// <returns></returns>
public static IUserService CreateUserService()
{
//string className = AssemblyName + "." + db + "UserService";
//return (IUserService)Assembly.Load(AssemblyName).CreateInstance(className);
if (db == "oracle")
{
return new OracleService.OracleUserService();
}
else
{
return new SQLServerService.SqlUserService();
}
}
}
}