创建数据会话层(将业务层与数据层解耦)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NCUT.BookShop.DAL;
using NCUT.BookShop.IDAL;
using NCUT.BookShop.Model;
namespace NCUT.BookShop.DALFactory
{
// 数据会话层(工厂类):1.封装了所有的数据操作类实例的创建,业务层通过数据会话层就可以获取具体的数据操作类实例。
//2.将业务层与数据层解耦
//3.为EF开放了一个统一的数据处理方法接口
public class DBSession:IDBSession
{
NCUTBookShopDBEntities db = new NCUTBookShopDBEntities();
private IUserInfoDal userInfoDal;
public IUserInfoDal UserInfoDal
{
get
{
if (userInfoDal == null)
{
userInfoDal = new UserInfoDal();
}
return userInfoDal;
}
set { userInfoDal = value; }
}
//作用:一个业务中有可能涉及到对多张表进行操作,为了减少与数据库连接次数,提高性能。我们应该将这次业务涉及到的数据添加到EF上下文中,并且打上标记,最后一次性提交给数据库进行处理。
public bool SaveChanges()
{
return db.SaveChanges()>0;
}
}
}
创建数据会话层接口
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NCUT.BookShop.IDAL
{
public interface IDBSession
{
IUserInfoDal UserInfoDal { get; set; }
}
}
用抽象工厂使DBSession和数据层完全解耦
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using NCUT.BookShop.IDAL;
namespace NCUT.BookShop.DALFactory
{
public class AbstractFactory
{
private static readonly string DalAssembly = ConfigurationManager.AppSettings["DalAssembly"];
private static readonly string DalNameSpace = ConfigurationManager.AppSettings["DalNameSpace"];
public static IUserInfoDal CreateUserInfoDal()
{
string fullClassName = DalNameSpace + ".UserInfoDal";
return CreateInstance(fullClassName
, DalAssembly) as IUserInfoDal;
}
public static object CreateInstance(string fullClassName, string assemblyPath)
{
var assembly = Assembly.Load(assemblyPath);
return assembly.CreateInstance(fullClassName);
}
}
}