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

前言

软件系统中老是但愿作到松耦合,项目的组织形式也是同样,本篇文章将介绍在ASP.NET CORE MVC中怎么样将Controller与主网站项目进行分离,而且对Areas进行支持。html

实践

1.新建项目

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

2.修改Mvc配置

在WebHostDemo项目中修改ConfigureServices函数:github

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程序集注入到主程序中了。固然还能够经过另外一种方式:shell

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。mvc

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

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项目中创建以下目录结构:
Areaside

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已经上传到群文件中,仅供参考。

相关文章
相关标签/搜索