A. 提出问题

First of all, it is certainly a good idea to put your model into a separate project. As you've discovered, this is trivial.

Regarding Controllers and Views, I don't see any obvious advantage to separating them for most basic projects, although you may have a particular need to do so in a particular application.

If you do choose to do this, then you will need to tell the framework how to find your controllers. The basic way to do this is by supplying your own ControllerFactory. You can take a look at the source code for the DefaultControllerFactory to get an idea for how this is done. Subtyping this class and overriding the GetControllerType(string controllerName) method may be enough to accomplish what you're asking.

Once you've created your own custom ControllerFactory, you add the following line to Application_Start in global.asax to tell the framework where to find it:

ControllerBuilder.Current.SetControllerFactory(new MyControllerFactory()); 

Update: Read this post and the posts it links to for more info. See also Phil Haack's comment on that post about:

ControllerBuilder.Current.DefaultNamespaces.Add(     "ExternalAssembly.Controllers"); 

...which is not a complete solution, but possibly good enough for simple cases.

B. 第一种解决方案--指定其它控制器的命名空间

How to call controllers in external assemblies in an ASP.NET MVC application

If your ASP.NET MVC is growing large, it’s likely that you are partitioning your controllers in different namespaces, or maybe even in different assemblies, and it might happen that you have controllers with the same in different namespaces.

Phil Haack and Steve Sanderson wrote some great write-ups on how to partition an ASP.NET application down into Areas, a concept that exists in MonoRail but not in the core ASP.NET MVC framework. The two posts above allow grouping both the controllers and the views, so if you want a complete solution to the aforementioned problem make sure you read them.

What I want to point out here is that both the two approaches above are based on a hidden feature of the framework and the way the ControllerFactory looks for controller class. So it can be used in your own hand-made “area grouping” solution.

Let’s start directly with the solution: if you add to a route a datatoken named “namespaces” with a list of namespaces, the controller factory will look in these namespaces.

Route externalBlogRoute = new Route(    "blog/{controller}/{action}/{id}",    new MvcRouteHandler()    );

externalBlogRoute.DataTokens = new RouteValueDictionary(    new    {         namespaces = new[] { "ExternalAssembly.Controllers" }    });

routes.Add("BlogRoute", externalBlogRoute);

With the MapRoute helper method the things are easier since one of the many overloads allows you to specify directly an array of strings:

routes.MapRoute(    "Default",    "{controller}/{action}/{id}",    new { controller = "Home", action = "Index", id = "" },    new[] { "ExternalAssembly.Controllers" });

This is easier than having to remember the name of the datatoken key.

The default controller factory already takes into account the namespaces datatoken. In fact it follows this flow:

  1. Look in the namespaces provided inside the route
  2. if not found, then will look into all the namespaces

This is useful if you have many controllers with the same name in different namespaces: by specifying the namespace in the route definition, you are limiting where the framework will look for the controller.

As last point, if the namespace is in an external assembly, you have to add it as reference of the ASP.NET MVC web application project, otherwise it will not probe it.

B. 第二种解决方案——指定程序集和命名空间(自定义控制器工厂)

ASP.NET MVC - Developing Custom ControllerFactory

ASP.NET MVC Framework has been around for quite sometime now.It has now moved to BETA from it's initial CTP versions.I am a very big fan of this framework for it's simplicity and extensibility.For the next few posts I would like discuss about the various extensibility points of this framework.In this post I will note down my observations about implementing a custom controller factory.

When adding a controller to a ASP.NET MVC Web application we see that the Controller name must end with "Controller" and it is recommended that Controller classes to be put inside a subfolder named "Controllers" in the web application directory.Now think of a situation where I have many controller classes and for better maintainability I need to put them into separate assemblies.In addition to that I need to load the controller classes in a configurable manner based on controller name in the URI.

This can be done by implementing a custom controller factory to instantiate the right controller class based on config settings.To do this we need to implement the interface System.Web.Mvc.IControllerFactory .The two methods in this interface are

  1. System.Web.Mvc.IController CreateController(System.Web.Routing.RequestContext requestContext, string controllerName) - To create the controller instance based on RequestContext and controller name
  2. void ReleaseController(System.Web.Mvc.IController controller) - Release the controller instance

Following is the sample code with very rudimentary implementation:

public class CustomControllerFactory : IControllerFactory
{

    public IController CreateController(System.Web.Routing.RequestContext requestContext, string controllerName)
    {

        string controllerType = string.Empty;
        IController controller = null;

        //Read Controller Class & Assembly Name from Web.Config
        controllerType = ConfigurationManager.AppSettings[controllerName];

        if (controllerType == null) throw new ConfigurationErrorsException("Assembly not configured for controller " + controllerName);

        //Create Controller Instance

        controller = Activator.CreateInstance(Type.GetType(controllerType)) as IController;
        return controller;

    }

    public void ReleaseController(IController controller)
    {
        //This is a sample implementation
        //If pooling is used write code to return the object to pool
        if (controller is IDisposable)
        {
            (controller as IDisposable).Dispose();

        }
        controller = null;
    }

}

Now the question comes how do we integrate this ControllerFactory with the application.This can be done by setting the Controller factory using System.Web.Mvc.ControllerBuilder in Application_Start event of Global.asax.cs

protected void Application_Start()
{
           RegisterRoutes(RouteTable.Routes);
           ControllerBuilder.Current.SetControllerFactory(typeof(SB.Web.Mvc.CustomControllerFactory));
  }

Lastly we need to add the config entries for the Controller classes and assemblies in Web.config as shown below:

<appSettings>
  <add key="Home" value="SB.Controllers.HomeController, SB.Controllers"/>
</appSettings>

We can enhance this further by adding features like pooling,instancing mode (Singleton) etc.

In my next post I will discuss about my observations about the extension points related to Views.

转载于:https://www.cnblogs.com/kevin-wang/archive/2011/08/01/2124091.html

MVC如何分离Controller与View在不同的项目相关推荐

  1. MVC如何分离Controller与View在不同的项目?

    <开心锤子>是一款以探索箱子护送角色到达目标点为核心的游戏,结合通过数字判断箱子中是否存在危机.加入探索.收集.竞技.玩家成长元素,并延伸出多种游戏模式.以休闲益智娱乐为轴心,卡通Q版风格 ...

  2. 通过源代码研究ASP.NET MVC中的Controller和View(二)

    通过源代码研究ASP.NET MVC中的Controller和View(一) 在开始之前,先来温习下上一篇文章中的结论(推论): IView是所有HTML视图的抽象 ActionResult是Cont ...

  3. 通过源代码研究ASP.NET MVC中的Controller和View(三)

    通过源代码研究ASP.NET MVC中的Controller和View(一) 通过源代码研究ASP.NET MVC中的Controller和View(二) 第三篇来了,上一篇我已经把VirtualPa ...

  4. ASP.NET MVC中controller和view相互传值的方式

    ASP.NET MVC中Controller向view传值的方式: ViewBag.ViewData.TempData 单个值的传递 Json 匿名类型 ExpandoObject Cookie Vi ...

  5. 【转载】ASP.NET MVC中Controller与View之间的数据传递总结

    在ASP.NET MVC中,经常会在Controller与View之间传递数据,因此,熟练.灵活的掌握这两层之间的数据传递方法就非常重要.本文从两个方面进行探讨: Ø Controller向View传 ...

  6. MVC的全名是Model View Controll

    MVC的全名是Model View Controller,是模型(model)-视图(view)-控制器(controller)的缩写,是一种软件设计典范.它是用一种业务逻辑.数据与界面显示分离的方法 ...

  7. ASP.NET MVC3中Controller与View之间的数据传递总结

    一.  Controller向View传递数据 1.       使用ViewData传递数据 我们在Controller中定义如下: [csharp] view plaincopy print? V ...

  8. ASP.NET中添加View与Razor引擎以及View解析和Controller向View传值

    场景 ASP.NET中MVC添加Controller以及访问其Action: https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/106 ...

  9. Controller向View传值方式总结

    From: http://www.cnblogs.com/guohu/p/4377974.html 总结发现ASP.NET MVC中Controller向View传值的方式共有6种,分别是: View ...

  10. DotNet Core 2.2 MVC Razor 页面编译为 View.dll 文件的解决方法

    DotNet Core 2.2 MVC Razor 页面编译为 View.dll 文件的解决方法 参考文章: (1)DotNet Core 2.2 MVC Razor 页面编译为 View.dll 文 ...

最新文章

  1. COM:中科院遗传发育所发表“重组菌群体系在根系微生物组研究中应用”的重要综述
  2. Spring Cloud学习笔记-002
  3. 用HttpURLConnection发送http请求
  4. Linux系统IP地址
  5. MediaWiki初探:安装及使用入门
  6. 【CSS】CSS 的优先级总结
  7. Python入门-散点图绘制
  8. 学画画软件app推荐_5岁宝宝画画自学app推荐 快给宝宝找个合适的画画启蒙软件吧...
  9. Django简单入门
  10. arcgis里面怎么截图_怎么利用ARCGIS裁剪图像
  11. Redis基本类型之Set类型
  12. 电信云服务器装系统,天翼云主机重装系统的详细操作步骤
  13. CSS3绘制各种常见图形(圆形-椭圆形-三角形-五角星...)
  14. 【SearchString Algorithm Training】谭爷剪花布条
  15. 69A.Young Physicist
  16. 《设计模式之禅》-原型模式
  17. 极客日报:微信正式宣布开放外部链接;iPhone13预购开启导致苹果官网崩了;特斯拉将向车主提供新版 FSD
  18. [从零开始]用python制作识图翻译器·四
  19. MySQL安装2出现Typical_Mysql安装 - osc_c7lpn2ge的个人空间 - OSCHINA - 中文开源技术交流社区...
  20. OWC11绘制双轴图表

热门文章

  1. DELPHI 初学.
  2. 正在使用的文件如何删除?
  3. IDEA 这样配置注释模板,让你高出一个逼格!
  4. SQL 子查询怎么优化?写的很深!
  5. 电商购物核心架构演进:谁说架构思路会过时?
  6. 分布式系统如何设计,看看Elasticsearch是怎么做的
  7. 互联网创业公司残酷一幕:全员降薪,裁员凶猛与一夜解散
  8. 跟公司妹子交流了一下
  9. 如果突然多了一笔财富。。
  10. Android 11 Meetup 上海站!来了!