如何在多个项目中分离Asp.Net Core Mvc的Controller和Areas

时间:2024-05-01 08:07:38

前言

软件系统中总是希望做到松耦合,项目的组织形式也是一样,本篇文章将介绍在ASP.NET CORE MVC中怎么样将Controller与主网站项目进行分离,并且对Areas进行支持。

实践

1.新建项目

新建两个ASP.NET Core Web应用程序,一个命名为:WebHostDemo 另一个名为: Web.Controllers ,看名字可以知道第一个项目是主程序项目,第二个是存放Controller类和Areas的项目。

2.修改Mvc配置

在WebHostDemo项目中修改ConfigureServices函数:

public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddMvc(); var manager = new ApplicationPartManager(); var homeType = typeof(Web.Controllers.Areas.HomeController);
var controllerAssembly = homeType.GetTypeInfo().Assembly; manager.ApplicationParts.Add(new AssemblyPart(controllerAssembly));
manager.FeatureProviders.Add(new ControllerFeatureProvider()); var feature = new ControllerFeature(); manager.PopulateFeature(feature); services.AddSingleton(feature.Controllers.Select(t => t.AsType()).ToArray());
}

这样就将另一个项目中的Controller程序集注入到主程序中了。当然还可以通过另一种方式:

public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().ConfigureApplicationPartManager( m => {
var feature = new ControllerFeature();
m.ApplicationParts.Add(new AssemblyPart(controllerAssembly));
m.PopulateFeature(feature);
services.AddSingleton(feature.Controllers.Select(t => t.AsType()).ToArray());
});
}

这两种方式都可以注入Controller。

接下来修改Configure函数以,通过修改路由让Mvc支持Areas:

app.UseMvc(routes =>
{
routes.MapRoute(
name: "areaRoute",
template: "{area:exists}/{controller=Home}/{action=Index}/{id?}"); routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});

3.添加Areas

在Web.Controllers项目中建立如下目录结构:

Areas

        MyArea1
-Controllers
-Home.cs
-Views
-Home
Index.cshtml

4.为Controller添加Area

 [Area("MyArea1")]
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
}

最后

还有一件事很重要,当我们这么将项目进行分离后,DEBUG主程序将没办法找到Areas和Views目录,所以DEBUG时,要将这些目录Copy到主程序代码根目录,当然如果是发布程序的话就没有这个问题。

GitHub:https://github.com/maxzhang1985/YOYOFx 如果觉还可以请Star下, 欢迎一起交流。

.NET Core 开源学习群:214741894

Demo已经上传到群文件中,仅供参考。