我需要在Windows窗体应用程序中托管WCF服务,并从Windows服务调用WCF服务,该服务将数据发送到WCF服务,该服务将在Windows窗体应用程序(桌面应用程序)中显示它。
我该如何实现?我需要能够正常运行并且之前尝试过的代码。
答案 0 :(得分:5)
此代码应足以让您入门:
namespace TestWinform
{
public partial class Form1 : Form
{
private ServiceHost Host;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Host = new ServiceHost(typeof(MyWcfService));
Host.Open();
}
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
Host.Close();
}
}
}
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="TestWinform.MyWcfServiceBehavior">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
</behaviors>
<services>
<service behaviorConfiguration="TestWinform.MyWcfServiceBehavior"
name="TestWinform.MyWcfService">
<endpoint address="" binding="wsHttpBinding" contract="TestWinform.IMyWcfService">
<identity>
<dns value="localhost" />
</identity>
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
<host>
<baseAddresses>
<add baseAddress="http://localhost:8080/MyWcfService/" />
</baseAddresses>
</host>
</service>
</services>
</system.serviceModel>
</configuration>
请注意,当我向项目添加WCF服务时,Visual Studio已生成App.config。
答案 1 :(得分:2)
我建议你也使用一个线程:
private void Form1_Load(object sender, EventArgs e)
{
Task.Factory.StartNew(() =>
{
host = new ServiceHost(typeof(AssinadorWcf.AssinadorDigitalLecom));
host.Open();
});
}
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
try
{
host.Close();
}
catch
{
}
}
答案 2 :(得分:0)
使用以下代码在Windows窗体应用程序中托管WCF服务:
using System.ServiceModel.Channels;
ServiceHost host = new ServiceHost(typeof(MyNamespace.OrderService));
BindingElementCollection bec = new BindingElementCollection();
SymmetricSecurityBindingElement ssbe = new
SymmetricSecurityBindingElement();
ssbe.LocalServiceSettings.InactivityTimeout = new TimeSpan(0, 10, 0);
bec.Add(ssbe);
bec.Add(new TextMessageEncodingBindingElement());
bec.Add(new HttpsTransportBindingElement());
CustomBinding customBinding = new CustomBinding(bec);
host.AddServiceEndpoint(typeof(MyNamespace.IOrderService),customBinding,"http://localhost:8000/O
rderService/");