[英]Can I get/set data into WCF Service by Host?
我在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服務應用程序中讀取它
謝謝你的幫助。
您可以將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服務中公開具有公共屬性的值。 但事件也是必要的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.