Building ASP.NET Core web projects using razor libraries

Building ASP.NET Core web projects using razor libraries

Since the ASP.NET Core 2.1 release, it became finally easy to implement independent web libraries embedding everything it needs to set up a feature.This post is the first of a serie, that intends to explain how to set an ASP.NET Core razor MVC library to be used as an independent plugin.Such a lib is autonomous, can be packaged in a NuGet and activated just by refencing this project.

Structure of a MVC razor library

For this project, we will use the MVC structure. Being able to separate all the features in areas made the use of MVC much simpler than it used to be.

I recommend to follow the MVC base structure within Areas so it avoids conflicts and spaghettis.

Even though you have the choice between using MVC and Razor Pages, except in very simple or autonomous cases, I prefer to use MVC in a Feature in an Area rather than Pages.

Our project library folder structure will look like the following

project root
└── Areas
    ├── Feature1
    |   ├── Attributes        // any attribute specific to the area
    |   ├── Config            // config classes that may be injected from startup
    |   ├── Controllers       // controllers dedicated to the feature
    |   ├── Data              // datacontexts 
    |   ├── Extensions        // extensions dedicated to the area
    |   ├── Models            // database entities models
    |   ├── Services          // services
    |   ├── ViewModels        // viewmodels for the views and the controllers
    |   ├── Views             // views dedicated to the feature
    |   ├── wwwroot           // static files dedicated to the feature
    |   ├── FeatureErrorCodes.cs // error codes specific to the area
    |   ├── FeatureRoutes.cs  // route names to generate routes easily
    |   └── FeatureInit.cs    // extensions to init services and/or config in startup.cs
    ├── Feature2

How to build a razor library

This is the very easy part, to add a razor library, you may simply add a new project from the solution explorer:

> new project  > ASP.NET Core Web Application > Razor Class Library

Next you can prepare your folder structure by creating the folder architecture as presented above.

At this point most of the project will work as expected. However one useful feature feature is missing and has to be addressed:

wwwroot is not served by static files when in a library: How to include embedded static file in a razor library

What's next?

This part will be completed when the next articles will be posted.

Please sign-in to comment