Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to integrate MEF with ASP.NET MVC 4 and ASP.NET Web API
    text
    copied!<p>How does one integrate <a href="http://mef.codeplex.com/">Managed Extensibility Framework</a> (MEF) with ASP.NET MVC 4 and ASP.NET Web API in the same project?</p> <p>Consider an example application, with an MVC controller <code>HomeController</code> and a Web API controller <code>ContactController</code>. Both have a property of type <code>IContactRepository</code>, which they rely on MEF to resolve. The problem is how to plug MEF into MVC and Web API, so that instances are created via MEF.</p> <p><strong>HomeController:</strong></p> <pre><code>/// &lt;summary&gt; /// Home controller. Instruct MEF to create one instance of this class per importer, /// since this is what MVC expects. /// &lt;/summary&gt; [Export] [PartCreationPolicy(CreationPolicy.NonShared)] public class HomeController : Controller { [Import] private IContactRepository _contactRepository = null; public ActionResult Index() { return View(_contactRepository.GetAllContacts()); } } </code></pre> <p><strong>ContactController:</strong></p> <pre><code>/// &lt;summary&gt; /// Contact API controller. Instruct MEF to create one instance of this class per importer, /// since this is what Web API expects. /// &lt;/summary&gt; [Export] [PartCreationPolicy(CreationPolicy.NonShared)] public class ContactController : ApiController { [Import] private IContactRepository _contactRepo = null; public Contact[] Get() { return _contactRepo.GetAllContacts(); } } </code></pre> <p><strong>IContactRepository and ContactRepository:</strong></p> <pre><code>public interface IContactRepository { Contact[] GetAllContacts(); } [Export(typeof(IContactRepository))] public class ContactRepository : IContactRepository { public Contact[] GetAllContacts() { return new Contact[] { new Contact { Id = 1, Name = "Glenn Beck"}, new Contact { Id = 2, Name = "Bill O'Riley"} }; } } </code></pre> <p><strong>Contact:</strong></p> <pre><code>public class Contact { public int Id { get; set; } public string Name { get; set; } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload