ASP.NET MVC项目框架快速搭建实战

时间:2021-03-16 10:37:50

MVC项目搭建笔记----

项目框架采用ASP.NET MVC+Entity Framwork+Spring.Net等技术搭建,采用”Domain Model as View Model“的MVC开发模式,结合了抽象工厂的思想降低了三层之间的耦合,可以使用此套框架进行MVC项目的快速搭建。本框架的架构图如下:

ASP.NET MVC项目框架快速搭建实战

第一步(创建分类文件夹):

创建5个文件夹。分别为UI,Model,BLL,DAL,Common,以便于将各模块分类整理。

第二步(项目类库的创建):

在UI文件夹创建ASP.NET MVC4项目模板选择基本。

在Model文件夹创建Model类库项目。

在BLL文件夹创建BLL和IBLL类库项目。

在DAL文件夹创建DAL,IDAL,DALFactory类库项目。

在Common文件夹创建Common类库项目。

第三步(创建EF实体):

在数据库管理工具新建一个数据库,在Model层添加一个ADO.Net实体模型。

建好实体模型,右键选择“根据模型生成数据库”,也可以先建好数据库再右键“从数据库更新模型”。

第四步(各层内容的创建,重点!):

在DAL层创建一个EFDbContextFactory类。(CallContext是类似于方法调用的线程本地存储区的专用集合对象,并提供对每个逻辑执行线程都唯一的数据槽。数据槽不在其他逻辑线程上的调用上下文之间共享。)

 public class EFDbContextFactory
{
public static DbContext GetCurrentDbContext()
{
//线程内的单例:保证线程内实例唯一
DbContext db = (DbContext)CallContext.GetData("DbContext");
if (db == null)
{
db = new Model1Container(); CallContext.SetData("DbContext", db);
}
return db;
}
}

在DAL层创建一个BaseDal类,作为所有Dal的基类,封装crud方法。

 public class BaseDal<T> where T : class , new()
{
private DbContext db
{
get
{
return EFDbContextFactory.GetCurrentDbContext();
}
}
public virtual T Add(T entity)
{
db.Set<T>().Add(entity);
return entity;
} public virtual bool Update(T entity)
{
db.Entry(entity).State = EntityState.Modified;
return true;
} public virtual bool Delete(T entity)
{
db.Entry(entity).State = EntityState.Deleted;
return true; } public virtual int Delete(params int[] ids)
{
foreach (var item in ids)
{
var entity = db.Set<T>().Find(item);//如果实体已经在内存中,那么就直接从内存拿,如果内存中跟踪实体没有,那么才查询数据库。
db.Set<T>().Remove(entity);
}
return ids.Count();
} public List<T> LoadEntities(Expression<Func<T, bool>> whereLambda)
{
return db.Set<T>().Where(whereLambda).AsQueryable();
} public List<T> LoadPageEntities<S>(int pageSize, int pageIndex, out int total, Expression<Func<T, bool>> whereLambda, Expression<Func<T, S>> orderbyLambda, bool isAsc)
{
total = db.Set<T>().Where(whereLambda).Count();
if (isAsc)
{
return
db.Set<T>()
.Where(whereLambda)
.OrderBy(orderbyLambda)
.Skip(pageSize * (pageIndex - ))
.Take(pageSize)
.AsQueryable().ToList();
}
else
{
return
db.Set<T>()
.Where(whereLambda)
.OrderByDescending(orderbyLambda)
.Skip(pageSize * (pageIndex - ))
.Take(pageSize)
.AsQueryable().ToList();
}
}
}

在DAL层添加Dal类的T4模板(Dal类生成模板,生成各Dal类,包括继承类和接口,未给出,可自行编写)。T4模板生成的Dal类内容模板如下:

 public partial class UserInfoDal : BaseDal<UserInfo>,IUserInfoDal
{ }

在IDAL层添加IDal接口类的T4模板(未给出,自行编写)。T4模板生成的IDal类内容模板如下:

 public partial interface IUserInfoDal :IBaseDal<UserInfo>
{ }

在IDAL层添加IBaseDal接口类,作为IDal的基接口类,子接口只要继承此接口就可以实现crud(增删改查)及分页接口。

 public interface IBaseDal<T>
{
T Add(T entity);
bool Update(T entity);
bool Delete(T entity);
int Delete(params int[] ids);
List<T> LoadEntities(Expression<Func<T, bool>> whereLambda);
List<T> LoadPageEntities<S>(int pageSize, int pageIndex, out int total, Expression<Func<T, bool>> whereLambda, Expression<Func<T, S>> orderbyLambda, bool isAsc);
}

在IDAL层添加IDbSession接口类(此类作为DbSession类的约束,符合抽象的思想,不直接返回对象本身,而是返回他的接口,这样就不会直接对对象本身造成依赖,只要修改IDbSession)的T4模板(未给出,自行编写)。T4模板生成的IDbSession类内容模板如下:

 public partial interface IDbSession
{
IUserInfoDal UserInfoDal { get; }
int SaveChanges();
}

在DALFactory层添加DbSession类的T4模板(未给出,自行编写)。T4模板生成的DbSession类内容模板如下:

 public partial class DbSession :IDbSession
{ private IUserInfoDal _UserInfoDal;
public IUserInfoDal UserInfoDal {
get {
if (_UserInfoDal == null)
{
_UserInfoDal =new UserInfoDal();
}
return _UserInfoDal;
}
} public int SaveChanges()
{
//这里只需要调用当前线程内部的上下文SaveChange。
DbContext dbContext = EFDbContextFactory.GetCurrentDbContext();
return dbContext.SaveChanges();
}
}

在DALFactory层添加DbSessionFactory类,作为dbSession的工厂。

 public class DbSessionFactory
{
public static IDbSession GetDbSession()
{
IDbSession dbSession = (IDbSession) CallContext.GetData("DbSession");
if (dbSession == null)
{
dbSession = new DbSession();
CallContext.SetData("DbSession", dbSession);
return dbSession;
}
return dbSession;
}
}

在IBLL层创建IBaseService基接口类,作为所有IService接口类的crud公共约束。

 public interface IBaseService<T>
{
T Add(T entity);
bool Update(T entity);
bool Delete(T entity);
int Delete(params int[] ids);
List<T> LoadEntities(Expression<Func<T, bool>> whereLambda); List<T> LoadPageEntities<S>(int pageSize, int pageIndex, out int total,
Expression<Func<T, bool>> whereLambda
, Expression<Func<T, S>> orderbyLambda, bool isAsc);
int Savechanges();
}

在IBLL层添加IBLL接口类的T4模板(未给出,自行编写)。T4模板生成的IBLL接口类内容模板如下:

 public  partial interface IUserInfoService :IBaseService<UserInfo>
{ }

在BLL层创建BaseService类(作为所有Service类的基类,封装crud方法)。

 public abstract class BaseService<T> where T:class,new ()
{
public IDbSession DbSession
{
get { return DbSessionFactory.GetDbSession(); }
} public IBaseDal<T> CurrentDal; public int Savechanges()
{
return DbSession.SaveChanges();
} //要求所有的业务方法在执行之前必须给当前的CurrentDal 赋值。
public BaseService()
{
SetCurrentDal();
} //纯抽象方法:子类必须重写此方法。
public abstract void SetCurrentDal(); public virtual T Add(T entity)
{
return CurrentDal.Add(entity);
} public virtual bool Update(T entity)
{
CurrentDal.Update(entity); return this.Savechanges() > ;
} public virtual bool Delete(T entity)
{
return CurrentDal.Delete(entity); } public virtual int Delete(params int[] ids)
{
return CurrentDal.Delete(ids); } public List<T> LoadEntities(Expression<Func<T, bool>> whereLambda)
{
return CurrentDal.LoadEntities(whereLambda); } public List<T> LoadPageEntities<S>(int pageSize, int pageIndex, out int total, Expression<Func<T, bool>> whereLambda, Expression<Func<T, S>> orderbyLambda, bool isAsc)
{
return CurrentDal.LoadPageEntities(pageSize, pageIndex, out total, whereLambda, orderbyLambda, isAsc);
}
}

BaseService

在BLL层添加Services类的T4模板(未给出,自行编写)。T4模板生成的Service类内容模板如下:

 public partial class UserInfoService:BaseService<UserInfo>,IUserInfoService
{
public override void SetCurrentDal()
{
CurrentDal = DbSession.UserInfoDal;//对父类虚方法进行重写,以对Dal初始化。
}
}

第五步(配置Spring.Net框架):

在UI层添加lib文件夹(用于存放所有外部引用文件),将Spring.Net程序集文件夹放到lib文件夹下,UI层添加对Spring.Core,Spring.Web,Spring.Web.Extensions,Spring.Web.Mvc4程序集的引用。

在Global.asax文件里将MvcApplication类继承至SpringMvcApplication。

在Web.config文件里的<configuration>下的<configSections>节点下添加:

 <!--Spring配置节点-->
<sectionGroup name="spring">
<section name="context" type="Spring.Context.Support.MvcContextHandler, Spring.Web.Mvc4"/>
<section name="objects" type="Spring.Context.Support.DefaultSectionHandler, Spring.Core" />
</sectionGroup>
<!--Spring配置节点结束-->

在Web.config文件里的<configuration>节点下添加:

 <!--Spring配置节点-->
<spring> <context>
<!--选择XML文件的位置,3种方式,1 配置文件 2 定位文件 3 程序集-->
<!--<resource uri="config://spring/objects"/>-->
<!--resource uri="file://ServiceXml.xml"/-->
<!--resource uri="file://Controllers.xml"/-->
<resource uri="assembly://MyOA_BLL/MyOA_BLL/ServiceXml.xml"/>
<resource uri="assembly://MyOA/MyOA/Controllers.xml"/>
<!--<resource uri="assembly://SpringNetTest/SpringNetTest/objects1.xml"/>-->
</context>
<objects xmlns="http://www.springframework.net"> </objects> </spring>
<!--Spring配置节点结束-->

第六步(注入Service对象):

在BLL层添加生成ServiceXml配置文件的T4模板(Speing.Net属性注入方法请参见  http://www.cnblogs.com/sunniest/p/4125561.html   ),内容模板为:

 <objects xmlns="http://www.springframework.net">
<object name="UserInfoService" type="MyOA_BLL.UserInfoService, MyOA_BLL" singleton="false"> </object> </objects>

在Controller文件夹下的各Controller类中添加

 public IUserInfoService UserInfoService{get;set;}
IDbSession session = DbSessionFactory.GetDbSession();

用UserInfoService来调用业务逻辑的方法(通过Spring.net注入UserInfoService对象),在操作完成后用session的savechanges方法控制将对实体的操作保存到数据库中。

在UI层添加Controller.xml文件(用于向Controller类注入UserInfoService对象),内容模板为:

 <objects xmlns="http://www.springframework.net">
<object name="TestController" type="MyOA.Controllers.TestController, MyOA" singleton="false">
<property name="UserInfoService" ref="UserInfoService" />
</object> </objects>

至此项目基本框架搭建完成!

Controller调用业务逻辑层完整代码示例:

      public ActionResult Test()
{
return View();
} [HttpPost]
public ActionResult Test(string uname,string pwd)
{
UserInfo u =new UserInfo();
u.UserName=uname;
u.Pwd=pwd;
var t = UserInfoService.Add(u);
session.SaveChanges();
if(t.Id>){
return Content("注册成功!");
}
else{
return Content("注册失败!");
}
}

 

本文如果有什么错误或各位大神有什么建议和不同理解,可以回复交流一下,让本文达到抛砖引玉的目的。