简体   繁体   中英

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!

Try

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

not

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM