我在WindowsServiceHost上托管了WCF服务(以传达WindowsFormsApp<> WindowsServiceHost)
有没有办法从WCFService获取数据到WindowsServiceHost? 以其他方式(将数据从WindowsServiceHost设置为WCFService)
这就是我所做的:
已配置的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服务应用程序中读取它
感谢您的帮助。
答案 0 :(得分:3)
您可以将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服务中公开具有公共属性的值。但事件也是必要的。