我有一项服务,我需要从其他服务中获取其公共领域。该服务的代码:
public class MyService : ServiceBase
{
private readonly string strConfigXmlFileName = StartupObject.DEFAULT_CONFIG_XML;
private StartupObject _startupObject;
private readonly string serviceName = "My Service";
// this field is changed into service, we need to get its actual value
public string testString;
public MyService()
{
InitializeComponent();
_startupObject = new StartupObject(strConfigXmlFileName);
}
private void InitializeComponent()
{
// For Designer only:
ServiceName = "MyService";
}
protected override void Dispose(bool disposing)
{
if (_service != null)
_service.Dispose();
_service = null;
base.Dispose(disposing);
}
protected override void OnStart(string[] args)
{
try
{
_startupObject.startAll();
}
catch (Exception ex)
{
// some logging
}
}
protected override void OnStop()
{
try
{
_startupObject.stopAll();
}
catch (Exception ex)
{
// some logging
}
}
}
如何从其他项目中获取此字段testString?
我知道如何获取ServiceController并在未运行时启动它,也许有一种方法可以从ServiceController获取ServiceBase?
答案 0 :(得分:1)
这主要取决于上下文和可用的工具,但是我将根据自己的假设尝试回答此问题。在这里,通过“服务”,我假设一个流程实例而不是对象实例。
1)该字符串是只读/常量-我建议将其存储在一个小型数据库或跨应用程序共享的配置文件中,并在启动两个应用程序时读取此配置密钥。
2)您也可以尝试将此设置存储在共享内存中。更多信息是here。
Windows虚拟内存不允许您从其他进程轻松访问此变量。