Mike-Ward.Net

Asset Bundling in NancyFx - Part 3

In parts 1 and 2, I built an Asset Bundling facility for use in NancyFx. It provides a very easy (dare I say, super-duper-happy) method to bundling assets in NancyFx. In this last part, I’ll add asynchronous support.

Related:

In recent releases, NancyFx has added support for asynchronous route handling. Adding asynchronous support to the Asset Bundling code is easy using C#’s new async/await facility.

First I’ll extend the Bundle class to include three new functions that support async:

public static async Task StylesAsync(this IResponseFormatter formatter, IEnumerable<string> files, 
    IRootPathProvider rootPathProvider)
{
    return await formatter.GetBundleAsync(files, rootPathProvider, CssMimeType);
}

public static async Task ScriptsAsync(this IResponseFormatter formatter, IEnumerable<string> files, 
    IRootPathProvider rootPathProvider)
{
    return await formatter.GetBundleAsync(files, rootPathProvider, JsMimeType);
}

public static async Task GetBundleAsync(this IResponseFormatter formatter, IEnumerable<string> files,
            IRootPathProvider rootPathProvider, string contentType)
{
    var responseTask = new Task(() => GetBundle(formatter, files, rootPathProvider, contentType));
    responseTask.Start();
    return await responseTask;
}

https://gist.github.com/mike-ward/9100604

And here’s how to use it:

public SiteModule(IRootPathProvider rootPathProvider)
{
    Get["/"] = p => View["home"];

    Get["/styles", true] = async (p, ct) => await Response.StylesAsync(
        new[] {"css/pure-min.css", "css/styles.css"}, rootPathProvider);

    Get["/scripts", true] = async (p, ct) => await Response.ScriptsAsync(
        new[] {"js/third-party/angular.min.js", "js/app/app.js"}, rootPathProvider);
}

Easy, smeasy!

What’s next?

It might be fun to look into adding some of the other traditional asset bundling services like SASS and Coffeescript support. These are harder nuts-to-crack in that native .NET implementations do not exist. One thought I had was to translate libsass to C#. Suggestions for other features are welcomed!

← newer older →
.Net, Technology, Life, Whatever

Recent Posts

Checklist Buddy Available for Testing
Tweetz 2.0.0 Released
Tweetz 2.0 Beta
VSColorOutput 2.7 - Time Stamps
Fixed Focal-Length Eyeglasses, a Programmer's Best Friend
How to Choose the Right VPN Service
Two Handy Command Line Scripts
More... (1089)

Donate