搭建自己的框架WedeNet(四)

WedeNet2018.Web-UI层:
结构如下:

首先,在Controller中定义BaseController,以便加入统一处理逻辑,如下:

using log4net;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WedeNet2018.Common;

namespace WedeNet2018.Web.Controllers
{
    /// <summary>
    /// 控制器基类
    /// </summary>
    public class BaseController : Controller
    {
        protected ILog log { get; set; }
      
        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            base.OnActionExecuting(filterContext);
            log.Info("---进入BaseController---");
        }

    }
}

在这里我们也声明了log4net变量,可在其派生类中决定使用哪一种配置的log。
以默认控制器为例:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WedeNet2018.BussinessLogic;
using PagedList;
using WedeNet2018.Infrastructure;
using System.Text.RegularExpressions;
using WedeNet2018.Common;
using WedeNet2018.Common.Models;
using log4net;

namespace WedeNet2018.Web.Controllers
{
    public class HomeController : BaseController
    {
        private OrdersBussinessLogic orderBll;
        private ElongOrdersDetailsBussinessLogic elongBll;
        private EmployeesBussinessLogic employeeBll;

        public HomeController(OrdersBussinessLogic BLL, ElongOrdersDetailsBussinessLogic ElongBll, EmployeesBussinessLogic EmployeeBll)
        {
            log = LoggerHelper.WedeNetLogger;
            orderBll = BLL;
            elongBll = ElongBll;
            employeeBll = EmployeeBll;

            log.Info("----HomeController初始化完成。----");
        }

        public ActionResult Index(int? page)
        {
            log.InfoFormat("初始化首页数据,page={0}", page);
            int pageSize = 10;
            int pageNum = (page ?? 1);

            var orders = orderBll.GetOrders(46).OrderBy(o => o.Id);

            return View(orders.ToPagedList(pageNum,pageSize));
            
        }

        public ActionResult Create()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Create(Orders order)
        {
            if (string.IsNullOrEmpty(order.OrderSn))
            {
                ModelState.AddModelError("OrderSn", "OrderSn不能为空");
            }
            if (order.UserId<0)
            {
                ModelState.AddModelError("UserId", "UserId必须大于0");
            }
            if (string.IsNullOrEmpty(order.UserName))
            {
                ModelState.AddModelError("UserName", "UserName不能为空");
            }
            if (string.IsNullOrEmpty(order.UserMobile))
            {
                ModelState.AddModelError("UserMobile", "UserMobile不能为空");
            }

            if (string.IsNullOrEmpty(order.Email))
            {
                ModelState.AddModelError("Email", "Email不能为空");
            }
            else
            {
                if (!ModelState.IsValidField(order.Email) || !new Regex(@"\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*", RegexOptions.IgnoreCase).IsMatch(order.Email))
                {
                    ModelState.AddModelError("Email", "Email不是正确的格式");
                }
            }

            if (ModelState.IsValid)
            {
                order.MerchantId = 46;
                order.UserMobile = "18210928340";
                order.DeliveryTypeId = 0;
                order.ServiceCost = 0;
                order.DeliveryCost = 0;
                order.PayCardType = 0;
                order.Enabled = true;
                order.IsSettledUp = true;
                order.HasRecievePay = true;
                order.HaveGetRecievePay = true;
                order.Created = DateTime.Now;
                order.LastModified = DateTime.Now;
                order.PaySn = "";
                order.OrderType = 46;
                order.Satisfaction = 0;
                orderBll.Add(order);

                //插入ElongOrdersDetails表
                ElongOrdersDetails detail = new ElongOrdersDetails();
                detail.OrderGuid = Guid.NewGuid();
                detail.OrderSn = order.OrderSn;
                detail.OrderId = 0;
                detail.Status = order.Status;
                detail.Created = DateTime.Now;
                detail.LastModified = DateTime.Now;
                elongBll.Add(detail);
                orderBll.Commit();

                return RedirectToAction("Index");
            }

            return View();
        }

        public ActionResult Details(int id)
        {
            Orders order = orderBll.Find(id);
            return View(order);
        }

        public ActionResult Edit(int id)
        {
            Orders order = orderBll.Find(id);
            return View(order);
        }

        [HttpPost]
        public ActionResult Edit(Orders orderEdit)
        {
            Orders order = orderBll.Find(orderEdit.Id);
            if (string.IsNullOrEmpty(orderEdit.Email))
            {
                ModelState.AddModelError("Email", "Email不能为空");
            }
            else
            {
                if (!ModelState.IsValidField(orderEdit.Email) || !new Regex(@"\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*", RegexOptions.IgnoreCase).IsMatch(orderEdit.Email))
                {
                    ModelState.AddModelError("Email", "Email不是正确的格式");
                }
            }

            if (ModelState.IsValid) {
                order.Email = orderEdit.Email;
                order.Status = orderEdit.Status;
                order.ServiceCost = orderEdit.ServiceCost;
                orderBll.Update(order);
            }
            return RedirectToAction("Index");
        }

        public ActionResult Delete(int id)
        {
            orderBll.Delete(id);
            return RedirectToAction("Index");
        }

        public JsonResult GetEmployees() {
            ResponseBase<List<Employees>> result = new ResponseBase<List<Employees>>();
            try
            {
                var employees = employeeBll.GetAll().ToList();
                result.IsSuccess = true;
                result.Message = "查询成功!";
                result.resultCode = "200";
                result.ResultData = employees;
            }
            catch (Exception ex) {
                result.IsSuccess = false;
                result.Message = "查询异常!"+ex.Message;
                result.resultCode = "500";
            }

            return Json(result);
        }


    }
}

注意到了,我在构造函数中进行了一些初始化,有日志的,有需要用到的BussinessLogic处理类,这些BussinessLogic处理类是依赖NInject注入实例化的,而且这三个处理类是属于不同的UnitOfWork和dbcontext(OrdersBussinessLogic和ElongOrdersDetailsBussinessLogic属于IWedeUnitOfWorks,而EmployeesBussinessLogic属于IXF0816UnitOfWorks)。

这里要说一下日志,在这个控制器中我把基类的日志初始化为WedeNetLogger,其实要分类打印的日志可以有很多,如:

根据需要对日志进行分类,并且在控制器的构造函数中根据情况进行初始化。

Ninject映射

要配置NInject,就需要先实现一个工厂,如:

using Ninject;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using WedeNet2018.BussinessLogic;
using WedeNet2018.Infrastructure;
using WedeNet2018.Infrastructure.Components;

namespace WedeNet2018.Web.Controllers
{
    /// <summary>
    /// Ninject工厂类
    /// </summary>
    public class NinjectControllerFactory : DefaultControllerFactory
    {
        private IKernel ninjectKernel;

        public NinjectControllerFactory()
        {
            ninjectKernel = new StandardKernel();
            AddBindings();
        }

        private void AddBindings()
        {
            ninjectKernel.Bind<AbsWedeDBContex>().To<WedeDBContex>();
            ninjectKernel.Bind<IWedeUnitOfWorks>().To<WedeUnitOfWorks<AbsWedeDBContex>>().InSingletonScope();
            ninjectKernel.Bind<OrdersBussinessLogic>().ToSelf();
            ninjectKernel.Bind<ElongOrdersDetailsBussinessLogic>().ToSelf();
            
            ninjectKernel.Bind<AbsXF0816DBContex>().To<XF0816DBContex>();
            ninjectKernel.Bind<IXF0816UnitOfWorks>().To<XF0816UnitOfWorks<AbsXF0816DBContex>>().InSingletonScope();
            ninjectKernel.Bind<EmployeesBussinessLogic>().ToSelf();
        }

        protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
        {
            return controllerType == null ? null : (IController)ninjectKernel.Get(controllerType);
        }
    }
}

我在工厂类的AddBindings()方法里进行了各种映射关系配置。

实现了工厂以后,还需要在Global.asax中注册这个工厂类,如:

然后,我们就可以使用NInject了。

MVC4的Bundles

UI项目里往往需要加载很多js和css,一些通用的可以放在Bundles里让MVC帮忙,如:

bundles.Add(new ScriptBundle("~/bundles/jss").Include(
					"~/Scripts/jquery-{version}.js",
					"~/Bootstrap/js/bootstrap.js",
					"~/js/common.js",
					"~/js/layer/layer.js"
					));
bundles.Add(new StyleBundle("~/Content/css").Include(
			"~/Content/site.css",
			"~/Bootstrap/css/bootstrap.css",
			"~/Bootstrap/css/bootstrap-grid.css",
			"~/Bootstrap/css/bootstrap-reboot.css",
			"~/js/layer/skin/layer.css",
			"~/js/layer/skin/default/layer.css"
			));

然后,就可以在视图模板中使用了,如:

UI展示层主要说明的就这些,另外Bootstrap、layer、jQuery、H5+CSS3内容不介绍了。

posted @ 2018-08-01 14:13  skybirdzw  阅读(239)  评论(0编辑  收藏  举报