WCF自寄宿
WCF很早就出现了,然而我感受到能够让新手重点去学习WCF而不是WebService是最近两年。我相信大部分人初步了解WCF的时候会很痛苦,尤其是生成代理类,以及配置的问题。我本人其实比较讨厌配置编程,但喜欢轻量配置,因此也一直研究如何自己定义配置节点,去让WCF服务识别,然后重量级ABC操作由编码来完成。下面,我将会提供一个我本人用于学习其他知识需要使用WCF时的开发模式,另外说明,为了更好的说明,我将提供的都是精简版本,并不适合用于测试生产的例子。
1.定义适合自己的配置
public class WCFServiceElement : ConfigurationElement
{
[ConfigurationProperty(name: "ServiceName", IsRequired = false)]
public string ServiceName
{
get
{
return (base["ServiceName"] as string);
}
set
{
base["ServiceName"] = value;
}
} [ConfigurationProperty(name: "ServiceAssembly", IsRequired = false)]
public string ServiceAssembly
{
get
{
return (base["ServiceAssembly"] as string);
}
set
{
base["ServiceAssembly"] = value;
}
} [ConfigurationProperty(name: "InterfaceServiceName", IsRequired = false)]
public string InterfaceServiceName
{
get
{
return (base["InterfaceServiceName"] as string);
}
set
{
base["InterfaceServiceName"] = value;
}
} [ConfigurationProperty(name: "InterfaceServiceAssembly", IsRequired = false)]
public string InterfaceServiceAssembly
{
get
{
return (base["InterfaceServiceAssembly"] as string);
}
set
{
base["InterfaceServiceAssembly"] = value;
}
} [ConfigurationProperty(name: "IPAddress", IsRequired = false)]
public string IPAddress
{
get
{
return (base["IPAddress"] as string);
}
set
{
base["IPAddress"] = value;
}
} [ConfigurationProperty(name: "Binding", IsRequired = false)]
public string Binding
{
get
{
return (base["Binding"] as string);
}
set
{
base["Binding"] = value;
}
}
}
public class WCFServicesElementCollection : ConfigurationElementCollection
{
protected override ConfigurationElement CreateNewElement()
{
ConfigurationElement _element = new WCFServiceElement();
return _element;
} protected override object GetElementKey(ConfigurationElement element)
{
WCFServiceElement _element = (WCFServiceElement)element;
return _element.ServiceName;
} protected override string ElementName
{
get
{
return "WCFService";
}
} public override ConfigurationElementCollectionType CollectionType
{
get
{
return ConfigurationElementCollectionType.BasicMap;
}
}
}
public class WCFServiceSection : ConfigurationSection
{
[ConfigurationProperty(name: "", IsDefaultCollection = true, IsRequired = false)]
public WCFServicesElementCollection WCFServices
{
get
{
return (base[""] as WCFServicesElementCollection);
}
set
{
base[""] = value;
}
}
}
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="WCFServices" type="Basic.Configuration.WCFServiceSection,Basic.Data"/>
</configSections>
<WCFServices>
<WCFService ServiceName="AppManagementImplementation"
ServiceAssembly="Service.BackgroundManagement.Implementation"
InterfaceServiceName="IAppManagement"
InterfaceServiceAssembly="Service.BackgroundManagement.Interface"
IPAddress="http://192.168.1.4:8085/AppManagementService"
Binding="WSHttpBinding">
</WCFService>
</WCFServices>
</configuration>
这里注意的是configSections一定要放在第一行,这个倒是听让人无语的。当然配置可以用自己希望方式配置,我这里提供一个简单的思路。
2.定义适合自己的WCFServerConfigurationManagement
public abstract class WCFServerConfigurationManagement
{
private static HybridDictionary _Collection = new HybridDictionary(); public static void Register()
{
WCFServiceSection section = ConfigurationManager.GetSection("WCFServices") as WCFServiceSection;
if (null == section)
{
throw new NullReferenceException("未能识别WCFServices,请确认configSections配置节点");
} _Collection.Clear(); foreach (WCFServiceElement element in section.WCFServices)
{
Assembly assemblyInterfaceService = Assembly.Load(element.InterfaceServiceAssembly);
Assembly assemblyService = Assembly.Load(element.ServiceAssembly); Type typeInterface = assemblyInterfaceService.ExportedTypes.FirstOrDefault(type => type.Name.Equals(element.InterfaceServiceName));
Type typeImplement = assemblyService.ExportedTypes.FirstOrDefault(type => type.Name.Equals(element.ServiceName)); if (null == typeInterface && null == typeImplement)
{
throw new NullReferenceException("无法加载服务");
} ServiceHost _NewHost = new ServiceHost(typeImplement);
Binding binding = CreateBinding(element.Binding);
_NewHost.AddServiceEndpoint(typeInterface, binding, element.IPAddress); _NewHost.Opened += (sender, e) =>
{
#if DEBUG
Console.WriteLine($"服务:{element.ServiceName} 已经开启.");
#endif
};
_NewHost.Open();
}
} public static Binding CreateBinding(string bindingType)
{
Binding _Binding = default(Binding);
switch (bindingType)
{
case "BasicHttpBinding":
_Binding = new BasicHttpBinding();
break;
case "WSHttpBinding":
_Binding = new WSHttpBinding();
break;
case "WS2007HttpBinding":
_Binding = new WS2007HttpBinding();
break;
default:
throw new ArgumentNullException("根据接口名称无法匹配绑定类型");
} return _Binding;
}
}
这里主要用来根据配置动态配置WCF ServiceHost 和 Binding 的.然后再您的Custom Host 里面调用如下:
class Program
{
static void Main(string[] args)
{
WCFServerConfigurationManagement.Register(); Console.ReadLine();
}
}
3.定义适合自己的WCFClientConfigurationManagement
public abstract class WCFClientConfigurationManagement
{
private static HybridDictionary _Collection = new HybridDictionary(); public static void Register()
{
WCFServiceSection section = ConfigurationManager.GetSection("WCFServices") as WCFServiceSection;
if (null == section)
{
throw new NullReferenceException("未能识别WCFServices,请确认configSections配置节点");
} _Collection.Clear(); foreach (WCFServiceElement element in section.WCFServices)
{
_Collection.Add(element.InterfaceServiceName , element);
}
} public static Binding CreateBinding(string serviceName)
{
Binding _Binding = default(Binding);
WCFServiceElement element = _Collection[serviceName] as WCFServiceElement;
if (null == element)
{
Register();
element = _Collection[serviceName] as WCFServiceElement;
if (null == element)
{
throw new NullReferenceException("可能配置出现严重错误,根据接口名称无法获取配置文件信息.");
}
} switch (element.Binding)
{
case "BasicHttpBinding":
_Binding = new BasicHttpBinding();
break;
case "WSHttpBinding":
_Binding = new WSHttpBinding();
break;
case "WS2007HttpBinding":
_Binding = new WS2007HttpBinding();
break;
default:
throw new ArgumentNullException("根据接口名称无法匹配绑定类型");
} return _Binding;
} public static EndpointAddress CreateAddress(string serviceName)
{
WCFServiceElement element = _Collection[serviceName] as WCFServiceElement;
if (null == element)
{
Register();
element = _Collection[serviceName] as WCFServiceElement;
if (null == element)
{
throw new NullReferenceException("可能配置出现严重错误,根据接口名称无法获取配置文件信息.");
}
} EndpointAddress _Address = new EndpointAddress(element.IPAddress);
return _Address;
}
}
这里主要用来根据配置动态配置WCF Client 和 Binding 的。然后再您的客户端以及配置文件注册如下(我这里提供的是ASP.NET MVC 5 的环境):
public class MvcApplication : HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles); WCFClientConfigurationManagement.Register();
}
}
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
<section name="WCFServices" type="Basic.Configuration.WCFServiceSection,Basic.Data"/>
</configSections>
<WCFServices>
<WCFService InterfaceServiceName="IAppManagement"
IPAddress="http://192.168.1.4:8085/AppManagementService"
Binding="WSHttpBinding">
</WCFService>
</WCFServices>
</configuration>
4.定义适合自己的WCF ClientBase
public class WCFClient
{
public static TResult ClientInvoke<TChannel , TResult>(Func<TChannel , TResult> functionInvoke)
{
string _ServiceName = typeof(TChannel).Name;
Binding binding = WCFClientConfigurationManagement.CreateBinding(_ServiceName);
EndpointAddress address = WCFClientConfigurationManagement.CreateAddress(_ServiceName);
TChannel _channel = ChannelFactory<TChannel>.CreateChannel(binding, address);
TResult _Result = functionInvoke.Invoke(_channel);
return _Result;
}
}
以上交代完毕,当然提醒初步了解WCF的人IPAddress 配置也可以写*.svc地址,可以在自寄宿在Windows Service 里,也可以是IIS宿主环境。写到这里,希望这篇随笔能帮助到需要帮助的人,这也就是它的价值所在了。
WCF自寄宿的更多相关文章
- 创建WCF服务寄宿到IIS
一.WCF简介: Windows Communication Foundation(WCF)是由微软开发的一系列支持数据通信的应用程序框架,可以翻译为Windows 通讯开发平台. 整合了原有的win ...
- WCF技术剖析之四:基于IIS的WCF服务寄宿(Hosting)实现揭秘
原文:WCF技术剖析之四:基于IIS的WCF服务寄宿(Hosting)实现揭秘 通过<再谈IIS与ASP.NET管道>的介绍,相信读者已经对IIS和ASP.NET的请求处理管道有了一个大致 ...
- WCF自寄宿实现Https绑定
一.WCF配置 1 Address 将服务端发布地址和客户端访问地址都配置为https开始的安全地址.参考如下. <add key="SrvUrl" value=" ...
- 关于WCF引用方式之WCF服务寄宿控制台
1.创建解决方案WCFService 依次添加四个项目,如上图,Client和Hosting为控制台应用程序,Service和Service.Interface均为类库. 2.引用关系 Service ...
- WCF服务寄宿应用程序
1.先创建一个WCF服务库 2.创建一个Console控制台,服务将寄宿在该应用程序上,该程序一旦关闭,服务将停止. 控制台代码: using System; using System.Collect ...
- WCF服务寄宿到IIS
一.WCF简介: Windows Communication Foundation(WCF)是由微软开发的一系列支持数据通信的应用程序框架,可以翻译为Windows 通讯开发平台.整合了原有的wind ...
- WCF服务寄宿IIS与Windows服务 - C#/.NET
WCF是Windows平台下程序间通讯的应用程序框架.整合和 .net Remoting,WebService,Socket的机制,是用来开发windows平台上分布式开发的最佳选择.wcf程序的运行 ...
- WCF服务寄宿IIS与Windows服务
WCF是Windows平台下程序间通讯的应用程序框架.整合和 .net Remoting,WebService,Socket的机制,是用来开发windows平台上分布式开发的最佳选择.wcf程序的 ...
- 将使用netTcp绑定的WCF服务寄宿到IIS7上全记录 (这文章也不错)
原文地址:http://www.cnblogs.com/wengyuli/archive/2010/11/22/wcf-tcp-host-to-iis.html 摘要 在项目开发中,我们可能会适时的选 ...
随机推荐
- JS.中文乱码,Jsp\Servlet端的解决办法
JS.中文乱码,Jsp\Servlet端的解决办法 2010-03-08 15:18:21| 分类: Extjs | 标签:encodeuricomponent 乱码 urldecoder ...
- maven的聚合与继承
新建一个空的maven项目user-parent Pom.xml内容 <project xmlns="http://maven.apache.org/POM/4.0.0" x ...
- LINQ系列:LINQ to SQL Take/Skip
1. Take var expr = context.Products .Take(); var expr = (from p in context.Products select p) .Take( ...
- OpenCASCADE6.8.0 Reference Manual Serach Problem
OpenCASCADE6.8.0 Reference Manual Serach Problem eryar@163.com 1. Problem 有网友反映OpenCASCADE6.8.0的Refe ...
- Visulalize Boost Voronoi in OpenSceneGraph
Visulalize Boost Voronoi in OpenSceneGraph eryar@163.com Abstract. One of the important features of ...
- 白话贝叶斯理论及在足球比赛结果预测中的应用和C#实现
离去年“马尔可夫链进行彩票预测”已经一年了,同时我也计划了一个彩票数据框架的搭建,分析和预测的框架,会在今年逐步发表,拟定了一个目录,大家有什么样的意见和和问题,可以看看,留言我会在后面的文章中逐步改 ...
- Puppet简易入门
一.查看官方提供的下载源 https://docs.puppet.com/guides/puppetlabs_package_repositories.html 二. 选择对应系统的下载源 因为本机是 ...
- MySQL Range Optimization
8.2.1.3 Range Optimization MYSQL的Range Optimization的目的还是尽可能的使用索引 The range access method uses a sing ...
- 精彩 .NET 2015
英文原文:Understanding .NET 2015 Understanding 翻译为了解或理解,对于 .NET 来说,2015 年注定会更加精彩,所以标题就用了"精彩"这个 ...
- 【经验之谈】Git使用之Windows环境下配置
前言 安装 配置 关于git使用的几个问题 后记 关于代码托管,以前用过vss和svn,看博客或论坛的时候,经常有人提到github,有很多著名的开源软件都托管在github,想来肯定不错(莫笑),当 ...