Skip to content

Instantly share code, notes, and snippets.

@Boggin
Created March 24, 2015 14:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Boggin/23dd1d1bf75c81cb349c to your computer and use it in GitHub Desktop.
Save Boggin/23dd1d1bf75c81cb349c to your computer and use it in GitHub Desktop.
Register MEF for both ASP.NET MVC and Web API using conventions.
namespace Portal.Web
{
using System.Composition.Convention;
using System.Composition.Hosting;
using System.Reflection;
using System.Web.Http;
using System.Web.Http.Controllers;
public static class ContainerConfig
{
public static void RegisterMef(HttpConfiguration configuration)
{
var appAssemblies =
new[]
{
Assembly.GetAssembly(typeof(IValidationService)), // .Service
Assembly.GetAssembly(typeof(ILookups)), // .Data
Assembly.GetAssembly(typeof(ISpreadsheet)), // .Excel
Assembly.GetExecutingAssembly()
};
var resolver = CreateWithConventions(appAssemblies);
System.Web.Mvc.DependencyResolver.SetResolver(resolver); // MVC.
configuration.DependencyResolver = (System.Web.Http.Dependencies.IDependencyResolver)resolver; // WebAPI.
}
private static System.Web.Mvc.IDependencyResolver CreateWithConventions(Assembly[] appAssemblies)
{
var conventions = new ConventionBuilder();
conventions.ForTypesDerivedFrom<IHttpController>()
.Export();
conventions.ForTypesMatching(
t => t.Namespace != null && t.Namespace.StartsWith("Unsettling."))
.Export()
.ExportInterfaces();
var container = new ContainerConfiguration()
.WithAssemblies(appAssemblies, conventions)
.WithExport(AutoMapperConfig.MappingEngineInstance)
.CreateContainer();
return new MefDependencyResolver(container);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment