1.学习目的
1.项目中需要将Controller中程序代码独立出来,以程序集引用方式完成项目.
2.自定义View获取文件路径,达到项目存放层次要求.
比如:重庆->渝北->海王星->5F->左边 等目录需求
2.粗略总结
1.1 地址
RouteTable.Routes MVC中源码 查看AreaRegistration类实现
a.MVC中Global.asax执行Application_Start.AreaRegistration.RegisterAllAreas() 调用所有实现AreaRegistration类来编辑RouteTable.Routesb.RouteTable.Routes 中获取Controller的Name
1.2 控制器
ControllerBuilder.Current.SetControllerFactory(new IControllerFactory()) 中CreateController方法来创建Controller
public IController CreateController(RequestContext requestContext, string controllerName)
{
object controllerf = null;
string controller = controllerName + "Controller";
if (controller == "UnitTestController")
{
//自定义的,解耦
Assembly assem = Assembly.LoadFile(@"E:\Demo\RMSP-TEST1\ReferenceAssembly\RMSP.UnitTest.dll");
controllerf = assem.CreateInstance("RMSP.UnitTest.UnitTestController");
}
else
{
//自带的
controllerf = new RMSP.Controllers.HomeController();
}
return (IController)controllerf;
}
{
object controllerf = null;
string controller = controllerName + "Controller";
if (controller == "UnitTestController")
{
//自定义的,解耦
Assembly assem = Assembly.LoadFile(@"E:\Demo\RMSP-TEST1\ReferenceAssembly\RMSP.UnitTest.dll");
controllerf = assem.CreateInstance("RMSP.UnitTest.UnitTestController");
}
else
{
//自带的
controllerf = new RMSP.Controllers.HomeController();
}
return (IController)controllerf;
}
1.3 视图
a.ViewResultBase中代码如下:[SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly", Justification = "This entire type is meant to be mutable.")]
public ViewEngineCollection ViewEngineCollection
{
get
{
//默认情况下,ViewEngineCollection为空,则使用ViewEngines.Engines中的视图引擎
return _viewEngineCollection ?? ViewEngines.Engines;
}
set
{
_viewEngineCollection = value;
}
}
b.ViewEngines.Engines源代码
public static class ViewEngines
{
private readonly static ViewEngineCollection _engines = new ViewEngineCollection
{
//WebForm中的视图解析
new WebFormViewEngine(),
//Razor视图解析
new RazorViewEngine(),
};
public static ViewEngineCollection Engines
{
get
{
return _engines;
}
}
}
c.如果要重写返回视图,比如要修改其中的视图地址. MSPViewEngine参考RazorViewEngine中路径解析就可以自定义了.
如下图
/// <summary>
/// 自定义控制器
/// </summary>
public class MSPController : Controller
{
static MSPController()
{
}
protected override ViewResult View(IView view, object model)
{
return base.View(view, model);
}
protected override ViewResult View(string viewName, string masterName, object model)
{
if (model != null)
{
ViewData.Model = model;
}
ViewEngineCollection vecollection = new System.Web.Mvc.ViewEngineCollection();
vecollection.Add(new MSPViewEngine());
ViewResult vResult = new ViewResult
{
ViewName = viewName,
MasterName = masterName,
ViewData = ViewData,
TempData = TempData,
ViewEngineCollection = vecollection
};
return vResult;
}
}