Modular Javacript and Stylesheets in C#

Posted: 28 January 2017 in Development

Recently I needed to build independent Angular / ASP.NET WebAPI code blocks that could self-register with a host web application, a kind of modular architecture where client and server side functionality could be 'dropped in'. This type of modular architecture is pretty common in content management style applications, where you have a 'shell' application and you install plugins to add new functionality.

WebAPI controllers are pretty easy to make portable, but client side functionality on the other hand isn't quite so easy to deal with. There are a few options available but the route I took was to embed the resources I needed within the related assembly / dll file.

Embedded Resources

Using embedded client side resources requires a combination of techniques:

  • Embedded resources - Javascript, CSS, images etc. embedded in the modular dll files
  • EmbeddedResourceVirtualPathProvider to provide access to the embedded resources via their embedded path
  • A singleton class to act as a repository for script and style files so that modules can register the files that need to be loaded by the host application

AppAssetStore singleton

A singleton repository class allows independent modules to register files to a central store. I've used WebActivatorEx in each module to perform registration at application start up, so each module injects its own assets to the repository. Couple this with a few Html helper methods to render the assets to the page and you've got a pretty decent solution IMO.

Sample code

For a super simple example of this in action I have created a sample application on GitHub: https://github.com/protomatter/modular-scripts, take a look and tell me what you think!

comments powered by Disqus

Get in touch...

Drop us a line at contact@protomatter.co.uk, or call on +44(0) 28 417 54771.