Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/api/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# C如何从其他服务中访问公共服务字段或方法?_C#_Api_Service - Fatal编程技术网

C# C如何从其他服务中访问公共服务字段或方法?

C# C如何从其他服务中访问公共服务字段或方法?,c#,api,service,C#,Api,Service,我有一个服务,我需要从其他服务中获取它的公共字段。此服务的代码: public class MyService : ServiceBase { private readonly string strConfigXmlFileName = StartupObject.DEFAULT_CONFIG_XML; private StartupObject _startupObject; private readonly string serviceName = "My Servi

我有一个服务,我需要从其他服务中获取它的公共字段。此服务的代码:

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?

这主要取决于可用的上下文和工具,但我将根据自己的假设尝试回答这个问题。通过这里的服务,我假设一个流程实例而不是对象实例

1此字符串为只读/常量-我建议将其存储在小型数据库或跨应用程序共享的配置文件中,并在启动两个应用程序时读取此配置密钥

2您也可以尝试将此设置存储在共享内存中。更多信息是


Windows虚拟内存不允许您从其他进程轻松访问此变量。

为什么不能创建此类的实例并访问其公共字段?我需要连接到已创建并运行的进程。例如testString,既然您的字段是只读字段,其中包含静态数据,那么这又有什么关系呢?好的,我更改了代码的这一部分好的,我更改了代码的这一部分。我想从第一个服务中获取一些公共字段,这个字段在这个服务中的某个地方被更改了。如果这个字段可以更改,最简单的解决方案是使用消息传递协议。例如AMPQ。但这也取决于更改第一个服务的代码的能力。当字段值更改时,消息应该从第一个进程发布,然后在第二个进程中使用。消息负载显然是一个字段值。谢谢,据我所知,这是最好的方法。