Skip to content

Instantly share code, notes, and snippets.

@johncoder
Created April 27, 2012 16:05
Show Gist options
  • Save johncoder/2510431 to your computer and use it in GitHub Desktop.
Save johncoder/2510431 to your computer and use it in GitHub Desktop.
Auto Register Bundles in ASP.NET MVC
using System;
using System.Collections.Generic;
using System.Linq;
using YourMvcApp.Core.Bundlers;
using Microsoft.Web.Optimization;
namespace YourMvcApp.Core.Resources
{
public class BundleRegistration
{
public static void RegisterBundles(BundleCollection bundles)
{
var jsBundleTypes = GetBundleTypes("YourMvcApp.Core.Resources.JSBundles");
var cssBundleTypes = GetBundleTypes("YourMvcApp.Core.Resources.CSSBundles");
#if (DEBUG)
var jsBundlerType = typeof(PlainJsBundler);
var cssBundlerType = typeof(PlainCssBundler);
#else
var jsBundlerType = typeof(JsMinify);
var cssBundlerType = typeof(CssMinify);
#endif
CreateAndAddBundles(jsBundleTypes, jsBundlerType, bundles);
CreateAndAddBundles(cssBundleTypes, cssBundlerType, bundles);
}
private static IEnumerable<Type> GetBundleTypes(string @namespace)
{
return from type in typeof(BundleRegistration).Assembly.GetTypes()
where type.Namespace != null
&& type.Namespace.StartsWith(@namespace)
&& typeof (Bundle).IsAssignableFrom(type)
select type;
}
private static void CreateAndAddBundles(IEnumerable<Type> bundleTypes, Type bundlerType, BundleCollection bundles)
{
foreach (var type in bundleTypes)
{
var instance = (Bundle)Activator.CreateInstance(type, new[] { bundlerType });
bundles.Add(instance);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment