Search code examples
c#mef

MEF Exporting using RegistrationBuilder does not work


I am trying to populate a MEF Catalog using [Export] Attributes and the Registration Builder. However the service exported using attributes can be resolved, the one registered using the RegistrationBuilder cannot be resolved. Have a look at my code below:

static class Program
{
  [STAThread]
  static void Main()
  {
    // export service 2 using registration builder
    var builder = new RegistrationBuilder();
    builder.ForType<IService2>().Export<Service2>();

    var catalog = new AssemblyCatalog(Assembly.GetExecutingAssembly(), builder);
    var container = new CompositionContainer(catalog, CompositionOptions.DisableSilentRejection);
    container.SatisfyImportsOnce(builder);

    // service exported using attribute can be resolved
    var service1 = container.GetExport<IService1>();

    // throws 
    var service2 = container.GetExport<IService2>();
  }
}

// create two dummy services

public interface IService1 { }

public interface IService2 { }

// export service 1 with attribute
[Export(typeof(IService1))]
public class Service1 : IService1 { }

public class Service2 : IService2 { }

What am i doing wrong? Can somebody help me? Thanks!


Solution

  • Try

    builder.ForType<Service2>().Export<IService2>();
    

    not

    builder.ForType<IService2>().Export<Service2>();