博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Modular Web Application with ASP.NET Core
阅读量:6860 次
发布时间:2019-06-26

本文共 7418 字,大约阅读时间需要 24 分钟。

直接撸别人的文章,还未来得及翻译,见谅。

Background
There are few things we need to address to make our application modularized:

How can MVC know about our controllers when they are in other class libraries, in other folder and not being referenced by the host

How can the ViewEngine pick up the right location for the Views in modules
How to register services used in modules
How to serve static file: js, css, image for modules
How to register domain entities in modules to DbContext

Using the code

Below is general folder structure I have come up with
图片描述

The Modular.WebHost is the ASP.NET Core project and it will act as the host. It will bootstrap the app and load all the modules it found in the Modules folder.

Each module contains all the stuff for itself to run including Controllers, Services, Views and event static files.

For easy development, in the visual studio solution I create a "Modules" solution items and add module projects in Modular.WebHost/Modules physical folder.

In order to prevent Modular.WebHost to compile stuff in Modules folder, we need to exclude them in the project.json.

  1. First we will scan all the assemblies in each module and load them up

var moduleRootFolder = new DirectoryInfo(Path.Combine(_hostingEnvironment.ContentRootPath, "Modules"));    var moduleFolders = moduleRootFolder.GetDirectories();    foreach (var moduleFolder in moduleFolders)    {        var binFolder = new DirectoryInfo(Path.Combine(moduleFolder.FullName, "bin"));        if (!binFolder.Exists)        {            continue;        }        foreach (var file in binFolder.GetFileSystemInfos("*.dll", SearchOption.AllDirectories))        {            Assembly assembly = null;            try            {                 assembly = AssemblyLoadContext.Default.LoadFromAssemblyPath(file.FullName);            }            catch (FileLoadException ex)            {                if (ex.Message == "Assembly with same name is already loaded")                {                    // Get loaded assembly                    assembly = Assembly.Load(new AssemblyName(Path.GetFileNameWithoutExtension(file.Name)));                }                else                {                    throw;                }            }            if (assembly.FullName.Contains(moduleFolder.Name))            {                modules.Add(new ModuleInfo { Name = moduleFolder.Name, Assembly = assembly, Path = moduleFolder.FullName });            }        }    }

Then module assemblies will be added to MVC by ApplicationPart

var mvcBuilder = services.AddMvc();    foreach (var module in modules)    {        // Register controller from modules        mvcBuilder.AddApplicationPart(module.Assembly);    }
  1. For the view, a custom ModuleViewLocationExpander is used to help the view engine lookup up the right module folder the views

services.Configure
(options => { options.ViewLocationExpanders.Add(new ModuleViewLocationExpander()); });
public class ModuleViewLocationExpander : IViewLocationExpander    {        private const string _moduleKey = "module";        public IEnumerable
ExpandViewLocations(ViewLocationExpanderContext context, IEnumerable
viewLocations) { if (context.Values.ContainsKey(_moduleKey)) { var module = context.Values[_moduleKey]; if (!string.IsNullOrWhiteSpace(module)) { var moduleViewLocations = new string[] { "/Modules/Modular.Modules." + module + "/Views/{1}/{0}.cshtml", "/Modules/Modular.Modules." + module + "/Views/Shared/{0}.cshtml" }; viewLocations = moduleViewLocations.Concat(viewLocations); } } return viewLocations; } public void PopulateValues(ViewLocationExpanderContext context) { var controller = context.ActionContext.ActionDescriptor.DisplayName; var moduleName = controller.Split('.')[2]; if(moduleName != "WebHost") { context.Values[_moduleKey] = moduleName; } } }
  1. Each module contains a ModuleInitializer.cs where services for that module is registered

// Register dependency in modules    var moduleInitializerInterface = typeof(IModuleInitializer);    foreach(var module in modules)    {        // Register dependency in modules        var moduleInitializerType = module.Assembly.GetTypes().Where(x => typeof(IModuleInitializer).IsAssignableFrom(x)).FirstOrDefault();        if(moduleInitializerType != null && moduleInitializerType != typeof(IModuleInitializer))        {            var moduleInitializer = (IModuleInitializer)Activator.CreateInstance(moduleInitializerType);            moduleInitializer.Init(services);        }    }

Please note that services within modules already registered by Autofac

  1. And this is how I serve static files for modules

// Serving static file for modulesforeach(var module in modules){    var wwwrootDir = new DirectoryInfo(Path.Combine(module.Path, "wwwroot"));    if (!wwwrootDir.Exists)    {        continue;    }    app.UseStaticFiles(new StaticFileOptions()    {        FileProvider = new PhysicalFileProvider(wwwrootDir.FullName),        RequestPath = new PathString("/"+ module.SortName)    });}
  1. For Entity Framework

    Every domain entities need to inherit from Entity, then on the "OnModelCreating" method, we find them and register them to DbContext

private static void RegisterEntities(ModelBuilder modelBuilder, IEnumerable
typeToRegisters) { var entityTypes = typeToRegisters.Where(x => x.GetTypeInfo().IsSubclassOf(typeof(Entity)) && !x.GetTypeInfo().IsAbstract); foreach (var type in entityTypes) { modelBuilder.Entity(type); } }

Sometimes, we might also need to do some custom mappings for our model, let take look at the sample below

public class ModuleACustomModelBuilder : ICustomModelBuilder    {        public void Build(ModelBuilder modelBuilder)        {            modelBuilder.Entity
() .Property(x => x.Name).HasColumnName("TestName"); } }

All the classes that implement the ICustomModelBuilder will be hooked and called in the "OnModelCreating" of the ModularDbContext

private static void RegisterCustomMappings(ModelBuilder modelBuilder, IEnumerable
typeToRegisters) { var customModelBuilderTypes = typeToRegisters.Where(x => typeof(ICustomModelBuilder).IsAssignableFrom(x)); foreach(var builderType in customModelBuilderTypes) { if (builderType != null && builderType != typeof(ICustomModelBuilder)) { var builder = (ICustomModelBuilder)Activator.CreateInstance(builderType); builder.Build(modelBuilder); } } }
  1. Strong typed view

    There is a known issue with 1.0.0 on how MVC finds compilation assemblies for class libraries. We can workaround by adding the modules assemblies to the list of compilation assemblies directly.

var mvcBuilder = services.AddMvc()    .AddRazorOptions(o =>    {        foreach (var module in modules)        {            o.AdditionalCompilationReferences.Add(MetadataReference.CreateFromFile(module.Assembly.Location));        }    });

Yeah, and now we are done. Please checkout the source code for more details.

转载地址:http://cxxyl.baihongyu.com/

你可能感兴趣的文章
设计模式 系列记忆之 六大设计原则
查看>>
写给即将面试的你
查看>>
Android NDK开发之JNI基础
查看>>
Java程序员有话说 大专生毕业 6 年月薪 3W+:不从众也不普通
查看>>
D2 日报 2019年5月29日
查看>>
剑指Offer(java答案)(11-20)
查看>>
<HTTP权威指南>记录 ---- Web缓存
查看>>
springmvc+mybatis+dubbo+zookeeper
查看>>
漫话:如何给女朋友解释什么是乐观锁与悲观锁
查看>>
【许晓笛】49行代码就能发币?而且EOS连例子都给你了
查看>>
MySQL 索引机制背后的隐藏之道
查看>>
基于 Vue.js 的支持本地化储存记事本 SPA
查看>>
016-JDK8+可用的反编译工具(JD_GUI+Procyon)
查看>>
ARTS - Week 2
查看>>
区块链数字资产交易系统的种类,源中瑞小六说
查看>>
JavaScript中的浅拷贝与深拷贝
查看>>
Spring Boot RabbitMQ系列之基础概念
查看>>
探讨奇技淫巧
查看>>
8 个给前端的顶级 VS Code 扩展插件
查看>>
DIGEST认证
查看>>