如何在我的解决方案中使用相同的 CompositionConainer 对象(或其包含的程序集)?
How can I use the same CompositionConainer object (or it's contained assemblies) across my solution?
让我解释一个非常简单的例子来说明我需要什么。假设我有一个使用 MEF 的 VS 解决方案,并且具有以下广泛的项目结构和 classes.
- 服务器(项目)
- Server.cs(包含
Main
方法,用于启动应用程序。)
- 共享(项目)
- \合同
- ILogger.cs
- ISettings.cs
- 设置(项目)
- MySettings.cs(class 实施 ISettings)
- 记录器(项目
- MyLogger.cs(class 实施 ILogger)
鉴于...
- 以上所有项目都引用共享项目。
- 服务器是启动应用程序,它将所有目录初始化到一个应用程序容器中。
...我可以启动一个应用程序并从我的 Server
应用程序中初始化 MySettings
和 MyLogger
的单例。到目前为止,还不错。
现在,假设 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)
{
}
}
让我解释一个非常简单的例子来说明我需要什么。假设我有一个使用 MEF 的 VS 解决方案,并且具有以下广泛的项目结构和 classes.
- 服务器(项目)
- Server.cs(包含
Main
方法,用于启动应用程序。)
- Server.cs(包含
- 共享(项目)
- \合同
- ILogger.cs
- ISettings.cs
- \合同
- 设置(项目)
- MySettings.cs(class 实施 ISettings)
- 记录器(项目
- MyLogger.cs(class 实施 ILogger)
鉴于...
- 以上所有项目都引用共享项目。
- 服务器是启动应用程序,它将所有目录初始化到一个应用程序容器中。
...我可以启动一个应用程序并从我的 Server
应用程序中初始化 MySettings
和 MyLogger
的单例。到目前为止,还不错。
现在,假设 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)
{
}
}