Skip to content

Instantly share code, notes, and snippets.

@Kashkovsky
Last active June 8, 2016 15:20
Show Gist options
  • Save Kashkovsky/efbc0f497e932dc229b74590f5693cb0 to your computer and use it in GitHub Desktop.
Save Kashkovsky/efbc0f497e932dc229b74590f5693cb0 to your computer and use it in GitHub Desktop.
Dynamic discovery of mvc application assemblies
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Web.Compilation;
//Add to AssemblyInfo [assembly: PreApplicationStartMethod(typeof(ApplicationDynamicDiscovery), "Discover")]
namespace Web
{
public static class ApplicationDynamicDiscovery
{
public static IEnumerable<Assembly> Assemblies { get; set; }
public static void Discover()
{
AppDomain.CurrentDomain.AssemblyResolve += CurrentDomainAssemblyResolve;
Assemblies = new List<Assembly>();
var areasDir = new DirectoryInfo(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Areas"));
if (!areasDir.Exists)
{
return;
}
Assemblies = areasDir.GetDirectories()
.SelectMany(d => d.GetDirectories("bin", SearchOption.TopDirectoryOnly))
.SelectMany(d => d.GetFiles("AddService.ProviderWeb.*.dll", SearchOption.TopDirectoryOnly))
.Select(f => Assembly.LoadFile(f.FullName));
Assemblies.ToList().ForEach(BuildManager.AddReferencedAssembly);
}
private static Assembly CurrentDomainAssemblyResolve(object sender, ResolveEventArgs args)
{
if (args.RequestingAssembly != null)
{
return args.RequestingAssembly;
}
return Assemblies.SingleOrDefault(x => x.FullName == args.Name);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment