MVC project practice, in the three-tier architecture to achieve SportsStore-02, DbSession layer, BLL Layer

Source: Internet
Author: User

SportsStore is a master of ASP. the MVC project demonstrated in NET MVC3 framework (Third edition) covers many aspects of MVC, including: use DI container, URL optimization, navigation, paging, shopping cart, order, product management, Image Upload ...... it is a good MVC practice project, but it is not developed under a multi-layer framework, and there is still a distance from the real project. This series will try to implement the SportsStore project in a multi-layer framework and implement some functions in its own way.

 

This is the second article in the series, including:

■ 4. Three-tier Architecture Design
□4.2 create a unified portal for the DbSession layer data access layer
※4.2.1 explanation of MySportsStore. IDAL
※4.2.2 explanation of MySportsStore. DAL
□4.3 create a BLL Layer
※4.3.1 explanation of MySportsStore. IBLL
※4.3.2 explanation of MySportsStore. BLL

4.2 create a unified portal for the DbSession layer data access layer

The DbSession layer mainly implements three tasks:
1. Submit all changes
2. Obtain the IXXXRepository types
3. Execute SQL statements

 

4.2.1 explanation of MySportsStore. IDAL

→ IDbSession interface, a unified portal for the database access layer

Using System. data. sqlClient; namespace MySportsStore. IDAL {public interface IDbSession {// obtain all the warehousing interfaces IProductRepository ProductRepository {get; set ;}// save all the changes int SaveChanges (); // execute the SQL statement int ExeucteSql (string SQL, params SqlParameter [] paras );}}

→ IDbSessionFactory interface, abstract factory of IDbSession Interface

IDbSession instances are used in BaseRepository. We use the "Abstract Factory" to produce IDbSession instances.

namespace MySportsStore.IDAL{    public interface IDbSessionFactory    {        IDbSession GetCurrentDbSession();    }}

 

4.2.2 explanation of MySportsStore. DAL

→ DbSession: Implementation of the IDbSession Interface

using System.Data.Entity;using MySportsStore.IDAL;namespace MySportsStore.DAL{    public class DbSession : IDbSession    {        private IProductRepository _ProductRepository;        public IProductRepository ProductRepository        {            get            {                if (_ProductRepository == null)                {                    _ProductRepository = new ProductRepository();                }                return _ProductRepository;            }            set { _ProductRepository = value; }        }        public int SaveChanges()        {            IDbContextFactory dbFactory = new DbContextFactory();            DbContext db = dbFactory.GetCurrentThreadInstance();            return db.SaveChanges();        }        public int ExeucteSql(string sql, params System.Data.SqlClient.SqlParameter[] paras)        {            IDbContextFactory dbFactory = new DbContextFactory();            DbContext db = dbFactory.GetCurrentThreadInstance();            return db.Database.ExecuteSqlCommand(sql, paras);        }    }}

→ DbSessionFactory, which implements the IDbSessionFactory interface and accesses the entry instance at the unique data layer in the production thread

using System.Runtime.Remoting.Messaging;using MySportsStore.IDAL;namespace MySportsStore.DAL{    public class DbSessionFactory: IDbSessionFactory    {        public IDbSession GetCurrentDbSession()        {            IDbSession dbSession = CallContext.GetData(typeof (DbSession).FullName) as IDbSession;            if (dbSession == null)            {                dbSession = new DbSession();                CallContext.SetData(typeof(DbSession).FullName, dbSession);            }            return dbSession;        }    }}

 

4.3 create a BLL Layer

4.3.1 explanation of MySportsStore. IBLL

→ Add reference

● Add reference to MySportsStore. Model
● Add reference to MySportsStore. IDAL

→ IBaseService is the generic base interface implementation of all IXXXService interfaces, avoiding repeated parts of all IXXXService interfaces.

Using System; using System. linq; using System. linq. expressions; using MySportsStore. IDAL; namespace MySportsStore. IBLL {public interface IBaseService <T> where T: class, new () {// data layer access unified entry factory IDbSessionFactory DbSessionFactory {get; set ;} // data layer access unified entry IDbSession DbSessionContext {get; set ;}// query IQueryable <T> LoadEntities (Expression <Func <T, bool> wherelamties ); // query IQueryable by page <T> LoadPageEntities <S> (Expression <Func <T, bool> whereLambada, Expression <Func <T, S> orderBy, int pageSize, int pageIndex, out int totalCount, bool isASC); // query the total number of int Count (Expression <Func <T, bool> predicate); // Add T AddEntity (T entity ); // Add int AddEntities (params T [] entities) in batches; // Delete int DeleteEntity (T entity); // Delete int DeleteBy (Expression <Func <T, bool> wherelamty); // update T UpdateEntity (T entity); // update int UpdateEntities (params T [] entities) in batches );}}

Why do we need the DbSessionContext attribute?
-- This attribute can be used to obtain XXXRepository of the IXXXRepository type.

 

Why do we need the DbSessionFactory attribute?
-- The "Abstract Factory" attribute can be used to produce DbSessionContext instances.

 

→ IProductService: Implementation of the Basic interface IBaseService <Product>

using MySportsStore.Model;namespace MySportsStore.IBLL{    public interface IProductService : IBaseService<Product>    {             }}

 

4.3.2 explanation of MySportsStore. BLL

→ Add reference

● Add reference to MySportsStore. Model
● Add reference to MySportsStore. IDAL
● Add reference to MySportsStore. IBLL

 

→ BaseService

Using System; using System. collections. generic; using System. linq; using System. linq. expressions; using MySportsStore. DAL; using MySportsStore. IDAL; namespace MySportsStore. BLL {public abstract class BaseService <T>: IDisposable where T: class, new () {// data layer unified access portal factory attribute private IDbSessionFactory _ DbSessionFactory; public IDbSessionFactory DbSessionFactory {get {if (_ DbSessionFactory = null) {_ DbSessionFa Ctory = new DbSessionFactory ();} return _ DbSessionFactory;} set {_ DbSessionFactory = value ;}// unified data layer access entry attribute private IDbSession _ DbSessionContext; public IDbSession DbSessionContext {get {if (_ DbSessionContext = null) {_ DbSessionContext = DbSessionFactory. getCurrentDbSession ();} return _ DbSessionContext;} set {_ DbSessionContext = value ;}// current Repository, implemented in subclass-set protec in constructor using an abstract Method Ted IBaseRepository <T> CurrentRepository; // rewrite the method in the subclass to set the current Repository public abstract bool SetCurrentRepository (); public BaseService () {this. disposableObjects = new List <IDisposable> (); this. setCurrentRepository ();} // query public IQueryable <T> LoadEntities (Expression <Func <T, bool> wherelamties) {return this. currentRepository. loadEntities (wherelamties);} public IQueryable <T> LoadPage Entities <S> (Expression <Func <T, bool> whereLambada, Expression <Func <T, S> orderBy, int pageSize, int pageIndex, out int totalCount, bool isASC) {return this. currentRepository. loadPageEntities <S> (whereLambada, orderBy, pageSize, pageIndex, out totalCount, isASC);} // query the total number of public int Count (Expression <Func <T, bool> predicate) {return this. currentRepository. count (predicate);} // Add public T Add Entity (T entity) {this. currentRepository. addEntity (entity); DbSessionContext. saveChanges (); return entity;} // Add public int AddEntities (params T [] entities) {return this. currentRepository. addEntities (entities);} // Delete public int DeleteEntity (T entity) {this. currentRepository. deleteEntity (entity); return DbSessionContext. saveChanges ();} // batch Delete public int DeleteBy (Expression <Func <T, bool> wh EreLambda) {this. currentRepository. deleteBy (wherelamsion); return DbSessionContext. saveChanges ();} // update public T UpdateEntity (T entity) {this. currentRepository. updateEntity (entity); if (this. dbSessionContext. saveChanges () <= 0) {return null;} return entity;} // update public int UpdateEntities (params T [] entities) {return this. currentRepository. updateEntities (entities);} public IList <IDisposab Le> DisposableObjects {get; private set;} protected void AddDisposableObject (object obj) {IDisposable disposable = obj as IDisposable; if (disposable! = Null) {this. DisposableObjects. Add (disposable) ;}} public void Dispose () {foreach (IDisposable obj in this. DisposableObjects) {if (obj! = Null) {obj. Dispose ();}}}}}

BaseService is the generic base class implementation of all xxxservices.

 

Key Aspect 1: how to determine the current storage CurrentRepository in the BaseService subclass?
1. abstract base class BaseServic has the property CurrentRepository of IBaseRepository <T>
2. Set CurrentRepository by implementing the abstract method SetCurrentRepository () in the constructor of the abstract base class BaseServic
3. The subclass of BaseServic must override SetCurrentRepository () to determine the current CurrentRepository value.


Key Aspect 2: how to destroy CurrentRepository In the subclass of BaseService?
1. Create a set of IList <IDisposable> types in BaseService.
2. Provide an AddDisposableObject (object obj) method in BaseService, allowing subclass to put CurrentRepository into it
3. In the Dispose () method of BaseService, traverse all CurrentRepository for destruction.

 

→ ProductService, derived from BaseService <Product>, implements the IProductService interface.

using MySportsStore.IBLL;using MySportsStore.Model;namespace MySportsStore.BLL{    public class ProductService : BaseService<Product>, IProductService    {        public ProductService():base(){}        public override bool SetCurrentRepository()        {            this.CurrentRepository = DbSessionContext.ProductRepository;            this.AddDisposableObject(this.CurrentRepository);            return true;        }    }}

So far, the code implementation of the three-tier architecture has been completed.

 

The series "MVC project practices, implementing SportsStore in a three-tier architecture" includes:

MVC project practice, under the three-tier architecture to achieve SportsStore-01, EF Code First modeling, DAL layer MVC project practice, under the three-tier architecture to achieve SportsStore-02, DbSession layer, BLL layer MVC project practice, in the three-tier architecture to achieve SportsStore-03, Ninject controller factory MVC project practice, in the three-tier architecture to achieve SportsStore-04, achieve paging MVC project practice, in the three-tier architecture to achieve SportsStore-05, implement the MVC project practice of navigation, implement SportsStore-06 under the three-tier architecture, and implement shopping cart

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.