在很多教科书中都这样定义“接口”,接口用来定义一种操作的规范,它的命名为I开头,内部元素均为public,接口中的方法与属性只能定义声明,不能实现,它们只能通过子类去实现,这些东西不是我今天要说的重点,我今天要说的接口主要从它为了实现“操作的统一”去说明。
在Repository模块中,一般将数据层的“增,删,改,查”进行统一的封装,然后调用时,统一来自一个地方,这样可以大大降低维护的成本。在操作统一性上可以从两个方面去看,其一就是接口为操作提供统一的入口,代码可能是这样:
////// 通¨用?数y据Y库a访?问ê接ó口ú /// public interface IRepository { ////// 更ü新?记?录? /// /// void Update(TEntity entity) where TEntity : BaseEntity; /// /// [批ú量?]更ü新?记?录? /// /// void Update(IList list) where TEntity : BaseEntity; /// /// 插?入?记?录? /// void Insert(TEntity entity) where TEntity : BaseEntity; /// /// [批ú量?]插?入?记?录? /// void Insert(IList list) where TEntity : BaseEntity; /// /// 插?入?记?录?并¢返μ回?刚?刚?立¢即′插?入?的?状′态?视ó图? /// TEntity InsertGetIDENTITY(TEntity entity) where TEntity : BaseEntity; /// /// 删?除y有D多à个?参?数y控?制?的?对?象ó /// /// void Delete(TEntity entity) where TEntity : BaseEntity; /// /// 返μ回?默?认?结á果?集ˉ /// ///IQueryable GetModel () where TEntity : BaseEntity; /// /// 根ù据Y主÷键ü返μ回?实μ体? /// ///TEntity GetModelById (long id) where TEntity : BaseEntity; }
即数据层具体实体操作类型中要想对数据表进行CURD操作,必须从IRepository接口的实现类中去调用,这就是操作入口的统—;其实在方法参数中也实现了统一,我们可以看到参数类型为继承了BaseEntity这个类型(接口也是可以的,这里用的是抽象类)的泛型,这体现了传统参数的统一,在.net framworks中“类型的逆变”的特性。
我们在业务必层或者UI层(小项目可能不用业务层)调用时,代码可能是这样:
public class HomeController : BaseController { public HomeController() : this(new DataRepository()) { } public HomeController(IRepository iRepository) { _iRepository = iRepository; } public ActionResult Index() { List}userList = _iRepository.GetModel ().ToList(); return View(userList); }