如果有很多WCF服务需要寄宿,需要额外做一些工作:
总体思路是:先把这些WCF服务的程序集打包,然后利用反射加载各个WCF服务的程序集,按顺序一个一个寄宿。
先来看看我们需要寄宿的WCF服务:

实现步骤:
1、配置文件中打包这些WCF程序集信息。

2、需要自定义配置节点以及实现读取自定义配置节点的方法。
在configSections节点增加配置:

 <section name="ValidServices"
type="Mdtit.XXX.Mall.Hosting.ValidServicesSection, Mdtit.XXX.Mall.Hosting" />

配置处理类实现如下:

using System;
using System.Collections.Generic;
using System.Reflection;
using System.Configuration;
using System.ServiceModel.Configuration;
using System.ServiceModel;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
using System.ServiceModel.Description;
using System.Text;
using Mdtit.XXX.Mall.Common; namespace Mdtit.XXX.Mall.Hosting
{
/// <summary>
/// Custom configuration section for valid service setting
/// </summary>
internal class ValidServicesSection : ConfigurationSection
{
[ConfigurationProperty("Services")]
public ValidServiceCollection ValidServices
{
get { return this["Services"] as ValidServiceCollection; }
}
} /// <summary>
/// Custom configuration element collection for valid service setting
/// </summary>
internal class ValidServiceCollection : ConfigurationElementCollection
{
protected override ConfigurationElement CreateNewElement()
{
return new ValidService();
} protected override object GetElementKey(ConfigurationElement element)
{
return ((ValidService)element).Type;
}
} /// <summary>
/// Custom configuration element for valid service setting
/// </summary>
internal class ValidService : ConfigurationElement
{
[ConfigurationProperty("Type")]
public string Type
{
get
{
return (string)this["Type"];
}
}
}
}

3、windows服务的Main函数

static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
static void Main()
{
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new XXXService()
};
ServiceBase.Run(ServicesToRun);
}
}

4、windows服务类:XXXService

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using Mdtit.XXX.Mall.Hosting;
using Mdtit.XXX.Mall.Common;
using System.ServiceModel; namespace Mdtit.XXX.Mall.Hosting.Service
{
public partial class XXXService : ServiceBase
{
/// <summary>
/// All avalilable services.
/// </summary>
static List<ServiceHost> _allHosts = new List<ServiceHost>(); public XXXService()
{
InitializeComponent();
} protected override void OnStart(string[] args)
{
try
{
ServiceManager.StartAllValidServices();
LogHelper.LogInformation("All WCF services started.");
}
catch (ApplicationException ex)
{
LogHelper.LogInformation(ex.Message);
}
} protected override void OnStop()
{
try
{
ServiceManager.CloseAllServices();
LogHelper.LogInformation("All WCF services stopped.");
}
catch (ApplicationException ex)
{
LogHelper.LogInformation(ex.Message);
}
}
}
}

其中,ServiceManager.StartAllValidServices() 和 ServiceManager.CloseAllServices()是用来批量处理WCF服务的。

5、ServiceManager类实现如下:

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Reflection;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.Text; using Mdtit.XXX.Mall.Common; namespace Mdtit.XXX.Mall.Hosting
{
/// <summary>
/// Helper class to start/stop services
/// </summary>
internal class ServiceManager
{
/// <summary>
/// Container for all valid services
/// </summary>
static List<ServiceHost> _AllHosts = new List<ServiceHost>(); /// <summary>
/// Start all valid services.
/// </summary>
public static void StartAllValidServices()
{
string entryLocation = Assembly.GetEntryAssembly().Location; Configuration conf = ConfigurationManager.OpenExeConfiguration(entryLocation); ValidServicesSection validServiceSettings
= ConfigurationManager.GetSection("ValidServices") as ValidServicesSection; if (validServiceSettings != null)
{
foreach (ValidService validService in validServiceSettings.ValidServices)
{
string typeToLoad = validService.Type; // Load the assembly dynamic
string assemblyName = typeToLoad.Substring(typeToLoad.IndexOf(',') + 1);
Assembly.Load(assemblyName); Type svcType = Type.GetType(typeToLoad);
if (svcType == null)
{
string errInfo = string.Format("Invalid Service Type \"{0}\" in configuration file.",
typeToLoad); LogHelper.LogError(errInfo);
throw new ApplicationException(errInfo);
}
else
{
OpenHost(svcType);
}
}
}
else
{
throw new ApplicationException("Application configuration for WCF services not found!");
}
} /// <summary>
/// Create a host for a specified wcf service;
/// </summary>
/// <param name="t"></param>
private static void OpenHost(Type t)
{
ServiceHost host = new ServiceHost(t); host.Opened += new EventHandler(hostOpened);
host.Closed += new EventHandler(hostClosed);
host.Open(); _AllHosts.Add(host);
} /// <summary>
/// Close all services
/// </summary>
public static void CloseAllServices()
{
foreach (ServiceHost host in _AllHosts)
{
if (host.State != CommunicationState.Closed)
{
host.Close();
}
}
} /// <summary>
/// Event handler for host opened
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private static void hostOpened(object sender, EventArgs e)
{
ServiceDescription svcDesc = ((ServiceHost)sender).Description; string svcName = svcDesc.Name;
StringBuilder allUri = new StringBuilder();
foreach (ServiceEndpoint endPoint in svcDesc.Endpoints)
{
allUri.Append(endPoint.ListenUri.ToString());
} LogHelper.LogInformation(string.Format("Service \"{0}\" started with url: {1}",
svcName, allUri.ToString()));
} /// <summary>
/// Event handler for host closed
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private static void hostClosed(object sender, EventArgs e)
{
ServiceDescription svcDesc = ((ServiceHost)sender).Description; string svcName = svcDesc.Name; LogHelper.LogInformation(string.Format("Service \"{0}\" stopped.", svcName));
}
}
}

6、开始寄宿
以管理员身份运行我们前面写好的windows服务程序:

结果:

WCF寄宿windows服务二的更多相关文章

  1. WCF寄宿windows服务一

    如果只是寄宿单个wcf服务,方法很简单,步骤:1.创建好一个windows服务.关于windows服务内容见:http://www.cnblogs.com/zhaow/p/7866916.html2. ...

  2. WCF 寄宿Windows以及控制台启动

    一:添加windows服务 二:修改XXXInstaller1的StartType=Automatic,修改ProcessInstaller1的Account=LocalSystem 三:在progr ...

  3. 微软 WCF的几种寄宿方式,寄宿IIS、寄宿winform、寄宿控制台、寄宿Windows服务

    WCF寄宿方式是一种非常灵活的操作,可以在IIS服务.Windows服务.Winform程序.控制台程序中进行寄宿,从而实现WCF服务的运行,为调用者方便.高效提供服务调用.本文分别对这几种方式进行详 ...

  4. WCF服务自我寄宿 Windows服务

    WCF寄宿有自我寄宿跟IIS寄宿 服务代码: [ServiceContract] ---服务契约 public interface ICustomerService { [OperationContr ...

  5. Windows服务二:测试新建的服务、调试Windows服务

    一.测试Windows服务 为了使Windows服务程序能够正常运行,我们需要像创建一般应用程序那样为它创建一个程序的入口点.像其他应用程序一样,Windows服务也是在Program.cs的Main ...

  6. WCF安装Windows服务

    安装图解: 安装命令: 1. 开始 ->运行 ->cmd2. cd到C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319(Framework版本号按I ...

  7. C#创建windows服务(二:创建和卸载windows服务)

    引用地址: https://docs.microsoft.com/zh-cn/dotnet/framework/windows-services/how-to-create-windows-servi ...

  8. WCF服务寄宿Windows

    windows服务的介绍 Windows服务应用程序是一种需要长期运行的应用程序,它对于服务器环境特别适合.它没有用户界面,并且也不会产生任何可视输出.任何用户消息都会被写进Windows事件日志.计 ...

  9. C#.NET 操作Windows服务承载WCF

    Windows服务的制作.安装可以参考这篇: C#.NET 操作Windows服务(安装.卸载) - runliuv - 博客园 (cnblogs.com) 本篇会在这个解决方案基础上,继续修改. 一 ...

随机推荐

  1. [MySql]MySql中外键设置 以及Java/MyBatis程序对存在外键关联无法删除的规避

    在MySql设定两张表,其中product表的主键设定成orderTb表的外键,具体如下: 产品表: create table product(id INT(11) PRIMARY KEY,name ...

  2. linux下的开源NFC协议栈

    1. 协议栈名称 neardal 2. 源码 https://github.com/connectivity/neardal.git 3. 由谁维护? intel 4. 基于neardal的nfc协议 ...

  3. 前端知识扫盲-VUE知识篇一(VUE核心知识)

    最近对整个前端的知识做了一次复盘,总结了一些知识点,分享给大家有助于加深印象. 想要更加理解透彻的同学,还需要大家自己去查阅资料或者翻看源码.后面会陆续的更新一些相关注知识点的文章. 文章只提出问题, ...

  4. Fragment向下兼容

    * android-support-v4都用这个包里的类* 让activity继承FragmentActivity* 获取管理器 getSupportFragmentManager();

  5. 【转载】网页JS获取当前地理位置(省市区)

    眼看2014又要过去了,翻翻今年的文章好像没有写几篇,忙真的或许已经不能成为借口了,在忙时间还是有的,就像海绵里的水挤挤总会有滴.真真的原因是没有学习过什么新的技术,工作过程中遇到的问题也不是非常难并 ...

  6. 数据包从物理网卡流经 Open vSwitch 进入 OpenStack 云主机的流程

    目录 文章目录 目录 前言 数据包从物理网卡进入虚拟机的流程 物理网卡处理 如何将网卡收到的数据写入到内核内存? 中断下半部分软中断处理 数据包在内核态 OvS Bridge(Datapath)中的处 ...

  7. 小D课堂-SpringBoot 2.x微信支付在线教育网站项目实战_5-4.微信授权一键登录开发之授权URL获取

    笔记 4.微信授权一键登录开发之授权URL获取     简介:获取微信开放平台扫码连url地址 1.增加结果工具类,JsonData;  增加application.properties配置      ...

  8. Android 单元测试学习计划

    网上查了一下Android单元测试相关的知识点,总结了一个学习步骤: 1. 什么是单元测试2. 单元测试正反面: 2.1. 重要性 2.2. 缺陷 2.3. 策略3. 单元测试的基础知识: 3.1. ...

  9. uni-app 实现热更新

    前端打包 app 即把写好的静态资源文件套壳打包成 app ,而热更新即下载并替换 app 内部的静态资源文件,实现 app 的版本升级. 在uni-app 中,我们是如何实现热更新的呢?下面来看代码 ...

  10. 打开svn时出现 R6034

    An application has made an attempt to load the C runtime library...... 最后发现是因为环境变量path里面有:E:\anacond ...