mvc4 基于Area实现插件模块化开发

时间:2023-03-08 16:34:46

  对于一个较大规模的Web应用,可以从功能上通过Area将其划分为为较小的单元。每个Area相当于一个独立的子系统,具有一套包含Model、Views和Controller在内

的目录结构和配置文件。一般来说,每个Area具有各自的路由规则,而基于Area的路由映射通过System.Web.Mvc.AreaRegistration注册。

  先来看下整体结构:

  mvc4 基于Area实现插件模块化开发

LoonMvc4是正常的mvc4项目,loon.plugin1和loon.plugin2是普通类库项目,接下来我们来看下怎么使得loog.plugin1成为一个独立的模块。

  mvc4 基于Area实现插件模块化开发

loon.plugin1是普通的类库项目。我们需要在类库中加入对mvc的支持,诸如引入:system.Web,System.Web.Mvc等使得该类库具有mvc的特质。接下来比较重要的一步,Area隆重登场,这里边需要注意,使用area 路由的话,引用必须包含System.Web.Mvc后方才可以使用。仔细看上边示意图,有一个文件名字较长就是“LoonPlugin1AreaRegistration.cs”。我们来关注一下LoonPlugin1AreaRegistration.cs这个文件。我们来看内部代码:

namespace loon.plugin1
{
public class LoonPlugin1AreaRegistration : AreaRegistration
{
public override string AreaName
{
get { return "LoonPlugin1"; }
}
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"LoonPlugin1",//路由名字,必须唯一
"LoonPlugin1/{controller}/{action}/{id}",//路由规则
new { controller = "Test", action = "Index", id = UrlParameter.Optional }//默认值
);
}
}
}

注:要使我们的Area发挥作用,必须继承AreaRegistration,而且我们的LoonPlugin1AreaRegistration 类的修饰符必须为 public。

完成了解完以上的代码之后,我们在loon.plugin1中创建一个controller,作为测试.如我们创建一个CustomerController.代码如下:

using System;
using System.Web;
using System.Web.Mvc;
using System.Collections.Generic;
using loon.plugin1.Domain;
using loon.plugin1.Repository;
using Microsoft.Practices.Unity; namespace loon.plugin1
{
public class CustomerController : Controller{ [Dependency]
public CustomerRepository customerRepository{get;set;} [HttpGet]
public ActionResult Index()
{
//Dictionary<string, object> dic = new Dictionary<string, object>();
//dic.Add("id", 100);
//dic.Add("name", "hello"); return Json(new {customer=this.customerRepository.GetAll(),message="loon.plugin1.CustomerController"}, JsonRequestBehavior.AllowGet);
}
}
}

我们还有重要的一步需要设置:在loon.plugin1类库中属性,将其生成目录放到LoonMvc4下,这一步超级重要,生成到主项目目录下之后,mvc就会根据路由找到并解析路由地址并完成请求:如图所示

 mvc4 基于Area实现插件模块化开发

 mvc4 基于Area实现插件模块化开发

  loon.plugin2的创建和配置和loon.plugin2一样。

然后整体运行解决方案,点击F5.

mvc4 基于Area实现插件模块化开发

注:我们可以反回去看一下,LoonPlugin1是我们loon.plugin1中定义路由的名字,customer是Controller的名字。

你看懂了吗?至于customer中的值是怎么来的,欢迎关注我么下篇博客 mvc4+nhibernate+mysql 插件式编程。

如果有什么问题,欢迎批评指正。