我在 WindowsServiceHost 上托管了 WCF 服务(用于与 WindowsFormsApp <> WindowsServiceHost 通信)
有没有办法从 WCFService 获取数据到 WindowsServiceHost? 并以其他方式(将数据从 WindowsServiceHost 设置为 WCFService)
这就是我所做的:
- 我做了一个WCF服务库的项目,实现了接口(interface),契约等。
- 我创建了新项目 - Windows 服务并添加了对项目 #1 和 System.ServiceModel 的引用
已配置的 app.conf:
<system.serviceModel> <bindings> <netTcpBinding> <binding name="netTcp"> <security mode="Message"> </security> </binding> </netTcpBinding> </bindings> <behaviors> <serviceBehaviors> <behavior name="mexBehavior"> <serviceMetadata httpGetEnabled="true"/> </behavior> </serviceBehaviors> </behaviors> <services> <service behaviorConfiguration="mexBehavior" name="KSPDJOBWinWCFService.KSPDJOBWinWCFService" > <endpoint address="KSPDJOBWinWCFService" binding="netTcpBinding" contract="KSPDJOBWinWCFService.IKSPDJOBWinWCFService" bindingConfiguration="netTcp" /> <host> <baseAddresses> <add baseAddress="http://localhost:8079"/> <add baseAddress="net.tcp://localhost:8090"/> </baseAddresses> </host> </service> </services>
我在 Windows 服务的 OnStart 方法中托管了 WCF
protected override void OnStart(string[] args) { host = new ServiceHost(typeof(KSPDJOBWinWCFService.KSPDJOBWinWCFService)); host.Open(); }
添加了带有 WinformsClient 应用程序(作为 WCF 客户端)的新解决方案并测试了通信 - 一切正常。
问题是当我从 WinFormsClient 发送一个值到 WCF 服务,并想从 Windows 服务应用程序读取它
感谢您的帮助。
最佳答案
您可以将 WCF 服务实例保存在全局变量中并处理事件。在此示例中,WCF 服务 KSPDJOBWinWCFService
公开一个事件 EventA
,服务主机将处理它。您可以在此处处理 WCF 客户端发送的值。
public partial class Service : ServiceBase
{
private ServiceHost _host;
private KSPDJOBWinWCFService _instance;
protected override void OnStart(string[] args)
{
try
{
_instance = new KSPDJOBWinWCFService();
_instance.EventA += HandleEventA;
_host = new ServiceHost(_instance);
_host.Open();
}
catch (Exception ex)
{
// Logging
}
}
public void HandleEventA(object sender, CustomEventArgs e)
{
// do whatever you want here
var localVar = e.Value;
}
protected override void OnStop()
{
try
{
if (_instance != null)
{
_instance.Dispose();
}
_host.Close();
}
catch (Exception ex)
{
// Logging
}
}
}
WCF 服务随后会触发此事件以及从 WCF 客户端发送的值:
public class KSPDJOBWinWCFService : IKSPDJOBWinWCFService
{
public event EventHandler<CustomEventArgs> EventA;
public bool SomeWcfOperation(int value)
{
EventA?.Invoke(this, new CustomEventArgs(value));
return true;
}
}
创建满足您需求的事件参数:
public class CustomEventArgs : EventArgs
{
public int Value { get; set; }
public CustomEventArgs(int value)
{
Value = value;
}
}
您还可以在 WCF 服务中公开具有公共(public)属性的值。但事件也是必要的。
关于c# - 我可以通过主机将数据获取/设置到 WCF 服务中吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40591726/