title: using mef with asp.net mvc 3
body: <p>I'm trying to use MEF in my asp.net mvc 3 application, but I could not realise the injection. Here is the code:</p>
  
  <p>I have an interfaces class library which has:</p>
  
  <pre><code>namespace Namespace.Interfaces
  {
      public interface IMessenger
      {
          string GetMessage();
      }
  }
  </code></pre>
  
  <p>And in another class library I have the class inherits from IMessenger:</p>
  
  <pre><code>namespace Namespace.Message
  {
      [Export(typeof(IMessenger))]
      public class Messenger : IMessenger
      {
          public Messenger()
          {
  
          }
  
          public string GetMessage() 
          {
              return "Mef Test!";
          }
      }
  }
  </code></pre>
  
  <p>I have a "Parts" directory in my application and I'm copying the dll of class library which contains class named "Messenger". </p>
  
  <p>In global.asax I have:</p>
  
  <pre><code>    private static CompositionContainer _container;
  
      protected void Application_Start()
      {
          AreaRegistration.RegisterAllAreas();
  
          RegisterGlobalFilters(GlobalFilters.Filters);
          RegisterRoutes(RouteTable.Routes);
  
          DirectoryCatalog catalog = new DirectoryCatalog(Server.MapPath("Plugins"), "*.dll");
          _container = new CompositionContainer(catalog);
          _container.ComposeParts();
  
          DependencyResolver.SetResolver(new MefDependencySolver(_container));
      }
  </code></pre>
  
  <p>Here is the MefDependencyResolver class:</p>
  
  <pre><code>public class MefDependencySolver : IDependencyResolver
  {
      public MefDependencySolver(CompositionContainer compositionContainer)
      {
          this.compositionContainer = compositionContainer;
      }
  
      private CompositionContainer compositionContainer;
  
      public object GetService(Type serviceType)
      {
          string name = AttributedModelServices.GetContractName(serviceType);
  
          return compositionContainer.GetExportedValueOrDefault&lt;object&gt;(name);
      }
  
      public IEnumerable&lt;object&gt; GetServices(Type serviceType)
      {
          return this.compositionContainer.GetExportedValues&lt;object&gt;(serviceType.FullName);
      }
  }
  </code></pre>
  
  <p>And at last I'm trying to use it in my controller like that:</p>
  
  <pre><code>public class HomeController : Controller
  {
      [ImportAttribute]
      public IMessenger _messenger { get; set; }
  
      public HomeController()
      {
  
      }
  
      public ActionResult Index()
      {
          ViewBag.Message = _messenger.GetMessage();
  
          return View();
      }
  }
  </code></pre>
  
  <p>But it doesn't create the _messenger object. I'm getting object reference not set to an instance of an object. What am I doing wrong? </p>
  
  <p>Thanks in advance,</p>