Click here to Skip to main content
13,146,376 members (46,255 online)
Click here to Skip to main content
Add your own
alternative version

Stats

46.8K views
2.3K downloads
82 bookmarked
Posted 28 Jun 2016

Modular Web Application with ASP.NET Core

, 16 Jan 2017
Rate this:
Please Sign up or sign in to vote.
How to support plugins in our web application with ASP.NET Core

You will need Visual Studio 2015 Update 3 with ASP.NET Core 1.0 installed to run this source code.

Introduction

Currently I am running an open source ecommerce written in .NET Core and I am looking for a solution to modularize my project. I have been researching for a few days. Some instructions have been found for example:

They seem not completed yet or too complicated for me. Struggling for a while, finally I can make it work. To be honest, I not sure this is best solution and I am looking for comments

Background

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

  1. How can MVC know about our controllers when they are in other class libraries, in other folder and not being referenced by the host
  2. How can the ViewEngine pick up the right location for the Views in modules
  3. How to register services used in modules
  4. How to serve static file: js, css, image for modules
  5. 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);
    }

2. For the view, a custom ModuleViewLocationExpander is used to help the view engine lookup up the right module folder the views

services.Configure<RazorViewEngineOptions>(options =>
    {
        options.ViewLocationExpanders.Add(new ModuleViewLocationExpander());
    });

And here is my ModuleViewLocationExpander.cs

    public class ModuleViewLocationExpander : IViewLocationExpander
    {
        private const string _moduleKey = "module";

        public IEnumerable<string> ExpandViewLocations(ViewLocationExpanderContext context, IEnumerable<string> 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;
            }
        }
    }

3. 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

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

// Serving static file for modules
foreach(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)
    });
}

5. 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<Type> 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<Sample>()
                .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<Type> 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);
            }
        }
    }

6. 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.

History

January 16, 2017: Added strong typed view

Points of Interest.

.NET Core and ASP.NET Core are very new, and it doesn't natively support building modular web application by default. Through combination features: dynamic loading assemblies from path, ApplicationPart, custom ViewLocationExpander and make use of StaticFileOptions, we can finally make it work. Thanks for reading.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Thiennn
NashTech
Vietnam Vietnam
A passionate developer who love coding and talking about technologies.

You may also be interested in...

Pro
Pro

Comments and Discussions

 
NewsUsage with ASP:NET Core 2.0 Pin
Matko Zurak21-Sep-17 3:19
memberMatko Zurak21-Sep-17 3:19 
GeneralMy vote of 5 Pin
Member 1125986118-Jan-17 3:15
memberMember 1125986118-Jan-17 3:15 
QuestionHow to implement that in ASP.NET MVC 5 ? Pin
Member 128896957-Dec-16 23:53
memberMember 128896957-Dec-16 23:53 
AnswerRe: How to implement that in ASP.NET MVC 5 ? Pin
Thiennn8-Dec-16 20:23
memberThiennn8-Dec-16 20:23 
QuestionModular migration Pin
tuabin3-Dec-16 0:31
membertuabin3-Dec-16 0:31 
AnswerRe: Modular migration Pin
Thiennn3-Dec-16 11:02
memberThiennn3-Dec-16 11:02 
QuestionLearning from this project Pin
Member 1115704226-Nov-16 20:14
memberMember 1115704226-Nov-16 20:14 
AnswerRe: Learning from this project Pin
Thiennn27-Nov-16 0:29
memberThiennn27-Nov-16 0:29 
Hi,

If you look at the source code that attached to this article or at [https://github.com/thiennn/trymodular]. Physically the code of modules are stored in the Modular.WebHost/Modules, they already there, so no need to copy. This approach make the development simpler but may be a bit harder when publish.

At [https://github.com/simplcommerce/SimplCommerce] we use another approach, which is the modules are kept separate from the WebHost, then we use a gulp task ( (src/SimplCommerce.WebHost/gulpfile.js) to copy the build output of modules to the WebHost. This task is bound to the AfterBuild event of Visual Studio or it can be run by command line.
Questionpleas see my question about u solution in stackoverflow Pin
Member 103237716-Nov-16 7:57
memberMember 103237716-Nov-16 7:57 
AnswerRe: pleas see my question about u solution in stackoverflow Pin
Thiennn6-Nov-16 19:19
memberThiennn6-Nov-16 19:19 
GeneralRe: pleas see my question about u solution in stackoverflow Pin
Member 103237717-Nov-16 5:14
memberMember 103237717-Nov-16 5:14 
QuestionExcellent + remove entity framework Pin
Member 1115704231-Oct-16 7:45
memberMember 1115704231-Oct-16 7:45 
AnswerRe: Excellent + remove entity framework Pin
Thiennn1-Nov-16 9:57
memberThiennn1-Nov-16 9:57 
Questioni got a exception when i call dbcontext.Set<TEntity>() Pin
chenflyxpA3-Oct-16 22:05
memberchenflyxpA3-Oct-16 22:05 
QuestionResharper CodeAnalysis Errors Pin
Member 1274833619-Sep-16 8:13
memberMember 1274833619-Sep-16 8:13 
AnswerRe: Resharper CodeAnalysis Errors Pin
Thiennn19-Sep-16 20:57
memberThiennn19-Sep-16 20:57 
GeneralRe: Resharper CodeAnalysis Errors Pin
Member 1274833619-Sep-16 21:07
memberMember 1274833619-Sep-16 21:07 
QuestionStrongly Typed Views Pin
Bill Shepherd14-Jul-16 12:23
memberBill Shepherd14-Jul-16 12:23 
AnswerRe: Strongly Typed Views Pin
Bill Shepherd14-Jul-16 16:30
memberBill Shepherd14-Jul-16 16:30 
AnswerRe: Strongly Typed Views Pin
Thiennn14-Jul-16 17:25
memberThiennn14-Jul-16 17:25 
AnswerRe: Strongly Typed Views Pin
Thiennn15-Jul-16 11:33
memberThiennn15-Jul-16 11:33 
PraiseVery nice article Pin
Lam Do9-Jul-16 13:34
memberLam Do9-Jul-16 13:34 
GeneralRe: Very nice article Pin
Thiennn10-Jul-16 12:17
memberThiennn10-Jul-16 12:17 
QuestionVery good article Pin
Reader Man San6-Jul-16 11:03
professionalReader Man San6-Jul-16 11:03 
AnswerRe: Very good article Pin
Thiennn6-Jul-16 16:28
memberThiennn6-Jul-16 16:28 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.170915.1 | Last Updated 16 Jan 2017
Article Copyright 2016 by Thiennn
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid