2

I have an ASP.Net Core 3.1 app and I have a number of plugins that I load through MEF. The simplified interface looks like this:

public interface IImportPlugin
{
    string Name { get; }
    string Category { get; }
    string Title { get; }
    string Description { get; }
}

And a plugin class might look like this:

[Export(typeof(IImportPlugin))]
public sealed class ImportCustomers : IImportPlugin
{
    private ICustomerService customerService;
    //Other services...

    [ImportingConstructor]
    public ImportCustomers()
        : base()
    { 
        //Set properties
    }
}

How can I inject instances of the services into the plugin?

Ivan-Mark Debono
  • 15,500
  • 29
  • 132
  • 263

1 Answers1

1

As an answer to your question you have two solution either by using An Import Attribute or GetExports Methods .

For Import (Importing By Constructor):

[Export(typeof(IImportPlugin))]
public sealed class ImportCustomers : IImportPlugin
{
    private ICustomerService _customerService;
    //Other services...

    [ImportingConstructor]
    public ImportCustomers([Import(typeof(ICustomerService))] ICustomerService customerService)
      : base()
    { 
        //Set properties
        _customerService  = customerService ;
    }
}

For GetExports :

[Export(typeof(IImportPlugin))]
public sealed class ImportCustomers : IImportPlugin
{
    private ICustomerService _customerService;
    //Other services...

    [ImportingConstructor]
    public ImportCustomers()
      : base()
    { 
        //You need to use your composition container
        //to resolve your instance using ICustomerService interface
        _customerService  = Container.GetExports<ICustomerService>()
                                     .Single().Value;
    }
}
Georg
  • 5,626
  • 1
  • 23
  • 44
sayah imad
  • 1,507
  • 3
  • 16
  • 24
  • 2
    Your "GetExports"-version is called the Service-Locator Anti-pattern. You should not use it because it hides the dependencies of your `ImportCustomers`-class. Further, note that MEF also supports property injection. – Georg Nov 09 '20 at 09:48
  • 1
    @Georg thank you very much for your contribution :). – sayah imad Nov 09 '20 at 10:09
  • I don't understand, where is the magic that inject the Customer service when it is injected in the importing constructor using an Import attribute? – Jins Peter Jan 30 '23 at 18:28
  • @JinsPeter concretely all the magic happens at the level of the container, which contains all the binaries through which MEF will be able to import and export through a mechanism of reflection based on import and export attribute. – sayah imad Feb 23 '23 at 14:40