【问题标题】:How to use dependency injection with MEF?如何在 MEF 中使用依赖注入?
【发布时间】:2020-11-05 07:28:52
【问题描述】:

我有一个 ASP.Net Core 3.1 应用程序,并且我有许多通过 MEF 加载的 plugins。简化的界面如下所示:

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

插件类可能如下所示:

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

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

如何将服务实例注入插件?

【问题讨论】:

标签: c# asp.net-core mef


【解决方案1】:

作为对您问题的回答,您有两个解决方案,分别是使用导入属性或 GetExports 方法。

对于导入(按构造函数导入):

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

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

【讨论】:

  • 您的“GetExports”版本称为服务定位器反模式。你不应该使用它,因为它隐藏了你的 ImportCustomers-class 的依赖关系。此外,请注意 MEF 还支持属性注入。
  • @Georg 非常感谢您的贡献:)。
猜你喜欢
  • 2014-03-18
  • 2017-06-04
  • 1970-01-01
  • 2010-09-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-29
  • 1970-01-01
相关资源
最近更新 更多