简体   繁体   中英

How to use dependency injection with MEF?

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?

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;
    }
}

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