MVC4商城项目一:框架设计
代码已托管在 https://code.csdn.net/denghao156/ktnmb_mvc4
先上图,设计模式参考:ddmvc4.codeplex.com
一、unintofwork 设计模式 http://www.cnblogs.com/zxj159/p/3505457.html
Unit Of Work模式会记录所有对象模型修改过的信息,在提交的时候,一次性修改,并把结果同步到数据库。 这个过程通常被封装在事务中。所以在DAL中采用Unit Of Work模式好处就在于能够确保数据的完整性,如果在持有一系列业务对象(同属于一个事务)的过程中出现问题,就可以将所有的修改回滚,以确保数据始终处于有效状态,不会出现脏数据。
1.1:Kt.DAL.UnitOfWork
UnitOfWork 继承 DbContext 实现对实体模型的增删改查,通过base.SaveChanges() 来实现数据的更新,从而把缓存区的上下文更改的数据一次提交到数据来实现事务。
public UnitOfWork() : base("name=EntitiesDb") { this.Configuration.ProxyCreationEnabled = true; this.Configuration.LazyLoadingEnabled = true; } public void Commit() { base.SaveChanges(); } public void CommitAndRefreshChanges() { bool saveFailed = false; do { try { base.SaveChanges(); saveFailed = false; } catch (DbUpdateConcurrencyException ex) { saveFailed = true; ex.Entries.ToList() .ForEach(entry => { entry.OriginalValues.SetValues(entry.GetDatabaseValues()); }); } } while (saveFailed); } public void RollbackChanges() { base.ChangeTracker.Entries() .ToList() .ForEach(entry => entry.State = EntityState.Unchanged); }
1.2: Kt.DAL
基础仓储类对UnitOfWork 的引用来实现多个表实体的统一操作。
public class Repository<T> : IRepository<T> where T : class { #region Members IQueryableUnitOfWork _UnitOfWork; #endregion #region Constructor /// <summary> /// 创建仓储实例 /// </summary> /// <param name="unitOfWork">Associated Unit Of Work</param> public Repository(IQueryableUnitOfWork unitOfWork) { if (unitOfWork == (IUnitOfWork)null) throw new ArgumentNullException("unitOfWork"); _UnitOfWork = unitOfWork; }
1.3:Kt.Respository
User 表仓储类。
public class UserRepository : Repository<User>, IUserRepository { public UserRepository(UnitOfWork unitOfWork) : base(unitOfWork) { } }
1.4:Kt.Service
User 表类的业务层的实现
public class UserService : IUserService { private readonly IUserRepository _userRepository; public UserService(IUserRepository userRepository) { this._userRepository = userRepository; } public UserDto GetUserById(int id) { return KtMapper.CreateMap<User, UserDto>(_userRepository.Get(id)); } public void AddUser(UserDto userDto) { User user = KtMapper.CreateMap<UserDto, User>(userDto); _userRepository.Add(user); _userRepository.UnitOfWork.Commit(); }
二、Castle Windsor DI MVC控制器依赖注入
1.1、Kt.Web
创建注入工厂
/// <summary> /// 依赖注入工厂 /// </summary> public class WindsorControllerFactory : DefaultControllerFactory { private readonly IKernel kernel; public WindsorControllerFactory(IKernel kernel) { this.kernel = kernel; } public override void ReleaseController(IController controller) { kernel.ReleaseComponent(controller); } protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType) { if (controllerType == null) { throw new HttpException(404, string.Format("The controller for path '{0}' could not be found.", requestContext.HttpContext.Request.Path)); } return (IController)kernel.Resolve(controllerType); } }
1.2、 Dependency 注入容器
public void Install(IWindsorContainer container, IConfigurationStore store) { container.Register(Classes.FromThisAssembly() .BasedOn<IController>() .LifestyleTransient()); container.Register( Component.For<IQueryableUnitOfWork, UnitOfWork>().ImplementedBy<UnitOfWork>(), Component.For<IUserRepository, UserRepository>().ImplementedBy<UserRepository>(), Component.For<IUserService>().ImplementedBy<UserService>(), AllTypes.FromThisAssembly().BasedOn<IHttpController>().LifestyleTransient() ) .AddFacility<LoggingFacility>(f => f.UseLog4Net()); LoggerFactory.SetCurrent(new TraceSourceLogFactory()); EntityValidatorFactory.SetCurrent(new DataAnnotationsEntityValidatorFactory()); }
1.3、MvcApplication 应用程序启动时控制器的依赖注入容器的实现
public class MvcApplication : System.Web.HttpApplication { private readonly IWindsorContainer container; public MvcApplication() { this.container = new WindsorContainer().Install(new Dependency.Dependency()); } public override void Dispose() { this.container.Dispose(); base.Dispose(); } protected void Application_Start() { AreaRegistration.RegisterAllAreas(); WebApiConfig.Register(GlobalConfiguration.Configuration); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); var controllerFactory = new WindsorControllerFactory(container.Kernel); ControllerBuilder.Current.SetControllerFactory(controllerFactory); } }
具体代码的实现见框架源代码:https://code.csdn.net/denghao156/ktnmb_mvc4
预计用的工具有:
- Visual Studio 2012
- ASP.NET MVC 4 with Razor View Engine
- Entity Framework 5.0
- Castle Windsor for DI
- SQL Server 2008/2012
- bootstrapt & JQuery
- automapper
本节参见大神所写,日后想自己做一个商城出来,代码持续更新到 code.csdn.net ……