前言
軟件系統中總是希望做到松耦合,項目的組織形式也是一樣,本篇文章將介紹在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已經上傳到群文件中,僅供參考。