WedeNet2018.WedeWcfServices-WCF服务层:
结构如下:

就是定义了服务契约接口和服务类,以OrderServices为例,如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using WedeNet2018.Infrastructure;
using WedeNet2018.Infrastructure.WcfEntities;namespace WedeNet2018.WedeWcfServices
{[ServiceContract]public interface IOrderServices{[OperationContract]OrdersContract[] GetOrders(int orderType);[OperationContract]OrdersContract GetOrdersStr(int orderType);[OperationContract]void AddOrder(OrdersContract order);[OperationContract]void UpdateOrder(OrdersContract order);[OperationContract]void DeleteOrder(int id);}
}

实现类:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ServiceModel;
using WedeNet2018.Infrastructure;
using WedeNet2018.BussinessLogic;
using Ninject;
using WedeNet2018.Infrastructure.Components;
using SFast;
using WedeNet2018.Infrastructure.WcfEntities;namespace WedeNet2018.WedeWcfServices.Impl
{[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall, ConcurrencyMode = ConcurrencyMode.Single)]public class OrderServices : IOrderServices{private OrdersBussinessLogic orderBll { get; set; }public OrderServices() {IKernel ninjectKernel = new StandardKernel();ninjectKernel.Bind<AbsWedeDBContex>().To<WedeDBContex>();ninjectKernel.Bind<IWedeUnitOfWorks>().To<WedeUnitOfWorks<AbsWedeDBContex>>().InSingletonScope();ninjectKernel.Bind<OrdersBussinessLogic>().ToSelf();orderBll = ninjectKernel.Get<OrdersBussinessLogic>();}public OrdersContract[] GetOrders(int orderType){OrdersContract[] ret = null;try{IList<Orders> orders = orderBll.GetOrders(orderType).ToList();IList<OrdersContract> ordersContracts = new List<OrdersContract>();orders.ForEach(o => ordersContracts.Add(new OrdersContract() {  Id=o.Id,OrderSn=o.OrderSn}));ret = ordersContracts.ToArray();}catch (Exception ex){}return ret;}public OrdersContract GetOrdersStr(int orderType){OrdersContract ret = new OrdersContract();try{Orders order = orderBll.GetOrders(orderType).FirstOrDefault();if (order != null) {ret.Id = order.Id;ret.OrderSn = order.OrderSn;}}catch (Exception ex){}return ret;}public void AddOrder(OrdersContract order) { }public void UpdateOrder(OrdersContract order) { }public void DeleteOrder(int id) { }}
}

这里需要说明的是,服务实现类的构造函数里,也有NInject的映射配置,当然这里是按需配置的。

WedeNet2018.ServiceHosting-WCF服务寄宿层:
结构如下:

(需要说明的是,本层是一个windows服务)

服务寄宿层的App.config里配置WCF相关配置信息,如:

<?xml version="1.0" encoding="utf-8" ?>
<configuration><configSections><section name="ValidServices"type="WedeNet2018.ServiceHosting.ValidServicesSection, WedeNet2018.ServiceHosting" /></configSections><connectionStrings><add name="constring" connectionString="Data Source=.;Initial Catalog=MVCEF1;User ID=sa;Password=11111111;" providerName="System.Data.SqlClient" /><add name="xf0816Constring" connectionString="Data Source=172.18.105.63;Initial Catalog=Xinfu0816;User ID=test;Password=xinfuka;" providerName="System.Data.SqlClient" /></connectionStrings><startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" /></startup><ValidServices><Services><add Type="WedeNet2018.WedeWcfServices.Impl.OrderServices,WedeNet2018.WedeWcfServices" /><add Type="WedeNet2018.WedeWcfServices.Impl.UserServices,WedeNet2018.WedeWcfServices" /></Services></ValidServices><system.serviceModel><behaviors><endpointBehaviors><behavior name="endpointBehavior"><dataContractSerializer /></behavior></endpointBehaviors><serviceBehaviors><behavior name="WedeNetServerBehavior_order"><serviceMetadata httpGetEnabled="true" httpGetUrl="http://localhost:9999/WedeWcfServices/orderServices/metadata" /><serviceDebug httpHelpPageEnabled="true" httpsHelpPageEnabled="true"includeExceptionDetailInFaults="true" /></behavior><behavior name="WedeNetServerBehavior_user"><serviceMetadata httpGetEnabled="true" httpGetUrl="http://localhost:9999/WedeWcfServices/userServices/metadata" /><serviceDebug httpHelpPageEnabled="true" httpsHelpPageEnabled="true"includeExceptionDetailInFaults="true" /></behavior></serviceBehaviors></behaviors><bindings><wsHttpBinding><binding name="WedeWcfBinding" closeTimeout="00:01:00"openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"bypassProxyOnLocal="false" transactionFlow="false" hostNameComparisonMode="StrongWildcard"maxBufferPoolSize="524288" maxReceivedMessageSize="99965536"messageEncoding="Text" textEncoding="utf-8" useDefaultWebProxy="true"allowCookies="false"><readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"maxBytesPerRead="4096" maxNameTableCharCount="16384" /><reliableSession ordered="true" inactivityTimeout="00:10:00"enabled="false" /><security mode="None"><transport clientCredentialType="Windows" proxyCredentialType="None"realm="" /><message clientCredentialType="Windows" negotiateServiceCredential="true" /></security></binding></wsHttpBinding></bindings><services><service behaviorConfiguration="WedeNetServerBehavior_order" name="WedeNet2018.WedeWcfServices.Impl.OrderServices"><endpoint address="http://localhost:9999/WedeWcfServices/orderServices"behaviorConfiguration="endpointBehavior" binding="wsHttpBinding"bindingConfiguration="WedeWcfBinding" contract="WedeNet2018.WedeWcfServices.IOrderServices"><identity><dns value="localhost" /></identity></endpoint></service><service behaviorConfiguration="WedeNetServerBehavior_user" name="WedeNet2018.WedeWcfServices.Impl.UserServices"><endpoint address="http://localhost:9999/WedeWcfServices/userServices"behaviorConfiguration="endpointBehavior" binding="wsHttpBinding"bindingConfiguration="WedeWcfBinding" contract="WedeNet2018.WedeWcfServices.IUserServices"><identity><dns value="localhost" /></identity></endpoint></service></services></system.serviceModel>
</configuration>

ValidServices配置节点是批量寄宿服务时,读取配置的服务信息的,其实现如下:

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;namespace WedeNet2018.ServiceHosting
{/// <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"];}}}
}

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 System.Threading.Tasks;
using WedeNet2018.Common;namespace WedeNet2018.ServiceHosting
{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;LoggerHelper.ServicesLogger.Info("typeToLoad:" + typeToLoad);// Load the assembly dynamicstring assemblyName = typeToLoad.Substring(typeToLoad.IndexOf(',') + 1);LoggerHelper.ServicesLogger.Info("assemblyName:" + assemblyName);Assembly.Load(assemblyName);Type svcType = Type.GetType(typeToLoad);if (svcType == null){string errInfo = string.Format("Invalid Service Type \"{0}\" in configuration file.",typeToLoad);LoggerHelper.ServicesLogger.Info(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());}LoggerHelper.ServicesLogger.Info(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;LoggerHelper.ServicesLogger.Info(string.Format("Service \"{0}\" stopped.", svcName));}}
}

实现批量服务寄宿的代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceModel;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using WedeNet2018.Common;
using WedeNet2018.WedeWcfServices.Impl;namespace WedeNet2018.ServiceHosting
{public partial class WedeNet2018Services : ServiceBase{static List<ServiceHost> _allHosts = new List<ServiceHost>();public WedeNet2018Services(){InitializeComponent();}protected override void OnStart(string[] args){try{ServiceManager.StartAllValidServices();LoggerHelper.ServicesLogger.Info("All WCF services started.");}catch (ApplicationException ex){LoggerHelper.ServicesLogger.Info(ex.Message);}}protected override void OnStop(){try{ServiceManager.CloseAllServices();LoggerHelper.ServicesLogger.Info("All WCF services stopped.");}catch (ApplicationException ex){LoggerHelper.ServicesLogger.Info(ex.Message);}}}
}

最后,服务的安装和卸载.bat代码:
service_install.bat

@echo off
set /p var=是否要安装 WCF 服务(Y/N):
if "%var%" == "Y" (goto install) else (goto batexit):install
copy C:\Windows\Microsoft.NET\Framework64\v4.0.30319\InstallUtil.exe  InstallUtil.exe /Y
call InstallUtil.exe E:\个人\Wede框架\WedeNet2018\WedeNet2018\WedeNet2018.ServiceHosting\bin\Debug\WedeNet2018.ServiceHosting.exe
call sc start "WedeNet2018Services"
pause:batexit
exit

service_unInstall.bat

@echo off
set /p var=是否要卸载 WCF服务(Y/N):
if "%var%" == "Y" (goto uninstall) else (goto batexit):uninstall
copy C:\Windows\Microsoft.NET\Framework64\v4.0.30319\InstallUtil.exe  InstallUtil.exe /Y
call InstallUtil.exe /u E:\个人\Wede框架\WedeNet2018\WedeNet2018\WedeNet2018.ServiceHosting\bin\Debug\WedeNet2018.ServiceHosting.exe
pause:batexit
exit

转载于:https://www.cnblogs.com/zhaow/p/9401133.html

搭建自己的框架WedeNet(五)相关推荐

  1. 如何搭建一个Spring框架超详细

    如何搭建一个Spring框架,首先我们要先了解Spring的核心构成部分 1.Spring 的构成 IOC 控制反转 spring 框架最核心的部分 DAO spring 对 访问数据库的支持 MVC ...

  2. 从零开始免费搭建自己的博客(五)——Typora + PicGo + GitHub/Gitee图床

    ​ 本文是博客搭建系列文章第五篇,其他文章链接: 从零开始免费搭建自己的博客(一)--本地搭建 Hexo 框架 从零开始免费搭建自己的博客(二)--基于 GitHub pages 建站 从零开始免费搭 ...

  3. 网站框架搭建——基于Django框架的天天生鲜电商网站项目系列博客(二)

    系列文章目录 需求分析--基于Django框架的天天生鲜电商网站项目系列博客(一) 网站框架搭建--基于Django框架的天天生鲜电商网站项目系列博客(二) 用户注册模块--基于Django框架的天天 ...

  4. Spring3.2.0-mybatis3.2.0 基于全注解搭建的后台框架-基础版

    2019独角兽企业重金招聘Python工程师标准>>> 摘要: Spring3.2.0-mybatis3.2.0 基于全注解搭建的后台框架-基础版 没有什么不可能  之前一直用的是自 ...

  5. 如何搭建html运行环境,搭建基于express框架运行环境的方法步骤

    一.Express简介 Express提供了一个轻量级模块,把Node.js的http模块功能封装在一个简单易用的接口中.Express也扩展了http模块的功能,使你轻松处理服务器的路由.响应.co ...

  6. python学习框架图-从零搭建深度学习框架(二)用Python实现计算图和自动微分

    我们在上一篇文章<从零搭建深度学习框架(一)用NumPy实现GAN>中用Python+NumPy实现了一个简单的GAN模型,并大致设想了一下深度学习框架需要实现的主要功能.其中,不确定性最 ...

  7. Django的学习需要掌握的一些基础和初步搭建自己的框架

    一.Django的学习需要掌握的一些基础 第一个需要注意的点:客户端发送过来的数据结构组成: 第二个需要注意的点:动态网页和静态网页 静态网页:用户发送请求,服务端找到对应的静态文件返回给浏览器,静态 ...

  8. 搭建App主流框架_纯代码搭建(OC)

    转载自:http://my.oschina.net/hejunbinlan/blog/529778?fromerr=EmSuX7PR 搭建主流框架界面 源码地址在文章末尾 达成效果 效果图 注:本文部 ...

  9. 怎样从0开始搭建一个测试框架_0

    怎样从0开始搭建一个测试框架_0 在开始之前,请让我先声明几点: 这个"从0开始"并不是说你不需要任何基础知识,而是指框架从无到有的过程,要开始搭建还是需要一定基础 请确保你已经掌 ...

  10. Python之web开发(一):python常用搭建网站的框架简介

    谈及WEB开发,使用java来的确要比python多的多.但实际上还是有很多大型的网站都是使用python搭建起来的,如国外最大的视频分析网站YouTube.国内的豆瓣.搜狐以及知乎等都是使用pyth ...

最新文章

  1. MySQL数据库数据类型以及INT(M)的含义
  2. ESP32-S3芯片与ESP32及ESP32-S2比较好在哪里呢?官方到目前还没有任何信息发布,我们先来猜看都会有哪些性能的提升
  3. RxSwift之常用高阶函数(操作符Operator)的说明和使用
  4. html段落前的空格,HTML空格:空格前后
  5. 路由器LED闪灯泄露数据
  6. C++面试中string类的一种正确简明的写法
  7. jeesit框架通过jBox获取弹窗信息
  8. 遗传算法matlab_当结构设计遇到遗传算法应用ANSYS和MATLAB联合优化设计探索(二)...
  9. 用python裁剪PDF文档
  10. 验证二叉树的前序序列化[抽象前序遍历]
  11. 通过IP地址连接两台电脑
  12. 南传法句经(摘选)03
  13. STM32-M3(野火)SD卡读写/移植znFAT文件访问系统
  14. python查询员工信息表
  15. 盘点大厂的那些开源项目 - 滴滴出行
  16. ADS仿真3_双枝短截线匹配电路设计
  17. Python中的蛇和梯子(单人游戏)
  18. Java基础。用户输入4个整数存放到数组中,通过代码找出数组中的最大值和最小值
  19. Java中快速掌握正则表达式
  20. Revit二次开发实现BIM盈利(以橄榄山快模为例解说) 视频讲座下载

热门文章

  1. Docker 1.12实践:Docker Service、Stack与分布式应用捆绑包
  2. 软考计算机英语词汇,软考计算机专业英语常用词汇(首字母I-O)
  3. 各位前辈请问你们的本科毕业论文的外文文献都是从哪里找的,我搜到的都是中国的翻译成英语的?...
  4. linux自动任务计划任务,「linux下的计划任务——只执行一次的定时任务」- 海风纷飞Blog...
  5. Java开发实习(入职经历)
  6. Python爬虫BeautifulSoup4小记
  7. 凯明启示录:倒闭风潮刚开始
  8. 安装pillow遇到的问题
  9. 有没有和作业帮一样的计算机,学霸君、学习宝和作业帮哪个好【对比】
  10. 使用Go语言实现单词翻译功能/simpledict 命令行词典