Created
March 24, 2015 14:54
-
-
Save Boggin/23dd1d1bf75c81cb349c to your computer and use it in GitHub Desktop.
Register MEF for both ASP.NET MVC and Web API using conventions.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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