WCF寄宿(Host)之自我寄宿(Self-Hosting)简单实例【Windows应用程序宿主】

 前言:

  以各种应用程序做自我寄宿的宿主原理方法大同小异,故:这儿直接上案例!


步骤一:创建服务契约和服务

1.新建解决方案:添加WCF服务库项目。

2、为了演示,我把自动生成的接口以及实现接口的类删除,自己添加一个WCF Service

3、撰写服务函数(同时,因为将原有的自动生成的接口与类删除了,故而需要将配置文件作相应的改动:)

namespace wcfself02
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService02" in both code and config file together.
[ServiceContract]
public interface IMe02
{
[OperationContract]
string showName(string str);
}
}
namespace wcfself02
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service02" in both code and config file together.
public class Me02 : IMe02
{

string IMe02.showName(string str)
{
string strr;
strr = str;
Console.WriteLine(strr);
return "啦啦啦" + strr;
}
}
}


步骤二:创建服务宿主

创建一个Windows应用程序来实现WCF服务的自我寄宿方式【添加Windows应用程序,引入WcfService.Library_01的引用,添加using System.ServiceModel;库文件引用。】,具体的实现以及代码如下所示:

 

Program.cs:

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Security.Principal;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace wcfhost02
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>

[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);

switch (CheckWindowsIdentity())
{
case 0: Application.Run(new Form1()); break;
case 1: Application.Exit(); break;
}

}

static int CheckWindowsIdentity()
{
WindowsIdentity identity = WindowsIdentity.GetCurrent();
WindowsPrincipal principal = new WindowsPrincipal(identity);
if (principal.IsInRole(WindowsBuiltInRole.Administrator)) return 0; //管理员

//普通用户,使用启动对象启动程序,以确保使用管理员身份运行创建启动对象
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.UseShellExecute = true;
startInfo.WorkingDirectory = Environment.CurrentDirectory;
startInfo.FileName = Application.ExecutablePath;
startInfo.Verb = "runas";
try
{
Process.Start(startInfo);
return 1;//普通用户
}
catch
{
return -1;//无权运行或用户放弃
}

}

}
}

 Form1.cs:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.ServiceModel;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using wcfself02;
namespace wcfhost02
{
public partial class Form1 : Form
{
Me02 MM = new Me02();
ServiceHost host = null;
public Form1()
{
InitializeComponent();
}

private void open_Click(object sender, EventArgs e)
{
if(host==null)
{
host = new ServiceHost(typeof(Me02));
host.Open();
}
}

private void close_Click(object sender, EventArgs e)
{
if(host !=null)
{
host.Close();
host = null;
}
}

private void Form1_Load(object sender, EventArgs e)
{
close_Click(sender, e);
}
}
}

利用配置文件的形式的方式进行终结点的添加和服务行为的定义

App.config[其中一种配置方式]:

<configuration>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="metadataBehavior">
<serviceMetadata httpGetEnabled="true" httpGetUrl="http://localhost:8733/Design_Time_Addresses/wcfself02/Me02/metadata"/>
</behavior>
</serviceBehaviors>
</behaviors>
<services>
<service behaviorConfiguration="metadataBehavior" name ="wcfself02.Me02">
<endpoint address="http://localhost:8733/Design_Time_Addresses/wcfself02/Me02/"
binding="wsHttpBinding"
contract="wcfself02.IMe02"/>
</service>
</services>
</system.serviceModel>
</configuration>

编译宿主程序,在所在的文件位置处,用管理员身份打开旗.exe文件;点击“Open”输入配置文件中的地址(http://localhost:8733/Design_Time_Addresses/wcfself02/Me02/metadata),可打开,点击“Close”,无法连接,说明创建成功!!

App.config[其中第一种配置方式]:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>

<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
</appSettings>
<system.web>
<compilation debug="true" />
</system.web>
<!-- When deploying the service library project, the content of the config file must be added to the host's
app.config file. System.Configuration does not support config files for libraries. -->
<system.serviceModel>
<services>
<service name="wcfself02.Me02">
<endpoint address="" binding="basicHttpBinding" contract="wcfself02.IMe02">
<identity>
<dns value="localhost" />
</identity>
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
<host>
<baseAddresses>
<add baseAddress="http://localhost:8733/Design_Time_Addresses/wcfself02/Me02/" />
</baseAddresses>
</host>
</service>
<service name="wcfself02.Me02">
<endpoint address="" binding="basicHttpBinding" contract="wcfself02.IMe02">
<identity>
<dns value="localhost" />
</identity>
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
<host>
<baseAddresses>
<add baseAddress="http://localhost:8733/Design_Time_Addresses/wcfself02/Me02/" />
</baseAddresses>
</host>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior>
<!-- To avoid disclosing metadata information,
set the values below to false before deployment -->
<serviceMetadata httpGetEnabled="True" httpsGetEnabled="True"/>
<!-- To receive exception details in faults for debugging purposes,
set the value below to true. Set to false before deployment
to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="False" />
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>

</configuration>

编译宿主程序,在所在的文件位置处,用管理员身份打开旗.exe文件;点击“Open”输入配置文件中的地址(http://localhost:8733/Design_Time_Addresses/wcfself02/Me02/),可打开,点击“Close”,无法连接,说明创建成功!!

特别注意!!在运行宿主应用程序时,一定以管理员权限运行宿主应用程序!!!


步骤三:创建客户端(引用服务,验证上面创建的服务)

创建一个控制台应用程序作为客户端引用上述的服务,添加服务应用时注意使服务是开启状态!!!

引用服务端的函数,可实现相应功能,这里不多赘述!

【欢迎转载】

 转载请表明出处: 乐学习

原文地址:https://www.cnblogs.com/JLZT1223/p/6061195.html