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

C# 如何在解决方案中使用相同的CompositionConainer对象(或它包含的程序集)?,c#,dependency-injection,mef,system.componentmodel,C#,Dependency Injection,Mef,System.componentmodel,让我解释一个我需要的非常简单的例子。假设我有一个VS解决方案,它使用MEF,具有以下广泛的项目和类结构 服务器(项目) Server.cs(包含用于启动应用程序的Main方法。) 共享(项目) \合同 ILogger.cs ISettings.cs 设置(项目) MySettings.cs(实现ISettings的类) 记录器(项目 MyLogger.cs(实现ILogger的类) 鉴于 以上所有项目都引用了共享项目 服务器是启动应用程序,它将所有目录初始化到应用程序容器中

让我解释一个我需要的非常简单的例子。假设我有一个VS解决方案,它使用MEF,具有以下广泛的项目和类结构

  • 服务器(项目)
    • Server.cs(包含用于启动应用程序的
      Main
      方法。)
  • 共享(项目)
    • \合同
      • ILogger.cs
      • ISettings.cs
  • 设置(项目)
    • MySettings.cs(实现ISettings的类)
  • 记录器(项目
    • MyLogger.cs(实现ILogger的类)
  • 鉴于

    • 以上所有项目都引用了共享项目
    • 服务器是启动应用程序,它将所有目录初始化到应用程序容器中
    …我可以从我的
    服务器
    应用程序中启动一个应用程序并初始化单个
    MySettings
    MyLogger
    。到目前为止,一切正常

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

    由于我使用的是MEF,我不想引用
    Logger
    项目中的
    设置
    项目。相反,我想使用MEF获取当前应用程序的
    设置
    单例,它在
    服务器
    应用程序开始时初始化,与服务器一起存在
    合成ionContainer

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

    服务器:

     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)
        {
        }
     }
    

    谢谢你的回答!当我周一回到办公室时,我会核实这一点。这似乎是解决办法。