如何在我的解决方案中使用相同的 CompositionConainer 对象(或其包含的程序集)?

How can I use the same CompositionConainer object (or it's contained assemblies) across my solution?

让我解释一个非常简单的例子来说明我需要什么。假设我有一个使用 MEF 的 VS 解决方案,并且具有以下广泛的项目结构和 classes.

  1. 服务器(项目)
    • Server.cs(包含 Main 方法,用于启动应用程序。)
  2. 共享(项目)
    • \合同
      • ILogger.cs
      • ISettings.cs
  3. 设置(项目)
    • MySettings.cs(class 实施 ISettings)
  4. 记录器(项目
    • MyLogger.cs(class 实施 ILogger)

鉴于...

...我可以启动一个应用程序并从我的 Server 应用程序中初始化 MySettingsMyLogger 的单例。到目前为止,还不错。

现在,假设 MyLogger 需要访问输出目录的设置文件。目录位置的值存储在 MySettings 对象中,该对象在 Server.cs 中初始化为 CompositonContainer

因为我使用的是 MEF,所以我不想在 Logger 项目中引用 Settings 项目。相反,我想使用 MEF 来获取当前应用程序 ISettings 单例,它在我的 Server 应用程序开始时初始化并存在于服务器 CompositionContainer.

如何使用 MEF 从 MyLogger 中正确访问 MySettings 单例?

服务器:

 class Services
 {
     [Import]
     public ISettings Settings 
     { 
         get; set;
     }

     [Import]
     public ILogger Logger 
     {
        get;  set;
     }

 }


 static void Main()
 {
     AggregateCatalog catalog = new AggregateCatalog();
     catalog.Add(new AssemblyCatalog(Assembly.GetAssembly(typeof(SettingsProject.MySettings));
     catalog.Add(new AssemblyCatalog(Assembly.GetAssembly(typeof(LoggerProject.MyLogger));


     Services services = new Services();

     CompositionContainer cc = new CompositionContainer(catalog);
     cc.ComposeParts(services);

     // services properties are initialized           

 }

设置项目

 [Export(typeof(ISettings)]
 class MySettings
 {
 }

记录器项目

 [Export(typeof(ILogger)]
 class MyLogger : ILogger
 {
    [ImportingConstructor]
    public MyLogger(ISettings settings)
    {
    }
 }