WCF重写ServiceHost,实现独立配置文件
有时我们需要将WCF的配置文件放在单独的配置文件中,而默认情况下WCF又是在web.config或app.config中去寻找服务配置。如果我们把配置文件放在另一个config文件中,如何让WCF知道呢?
答案就是重写ServiceHost。在重写中告诉WCF配置文件的路径。
public class MyServiceHost:ServiceHost
{
private string ConfigPath =System.AppDomain.CurrentDomain.BaseDirectory+ "MyApp.config"; public MyServiceHost(Type serviceType, params Uri[] baseAddresses) :
base(serviceType, baseAddresses)
{
} protected override void ApplyConfiguration()
{
// Check user config invalidation
if (!CheckConfigExist(ConfigPath))
{
// Use default config
base.ApplyConfiguration();
return;
}
//base.ApplyConfiguration();
// Use user config
ExeConfigurationFileMap execfgMap = new ExeConfigurationFileMap();
// Set user config FilePath
execfgMap.ExeConfigFilename = ConfigPath;
// Config info
Configuration cfg = ConfigurationManager.OpenMappedExeConfiguration(execfgMap,ConfigurationUserLevel.None);
// Gets all service model config sections
ServiceModelSectionGroup servicemodelSections = ServiceModelSectionGroup.GetSectionGroup(cfg); // Find serivce section matched with the name "this.Description.ServiceType.FullName"
if (!ApplySectionInfo(this.Description.ServiceType.FullName,servicemodelSections))
{
throw new Exception("ConfigApply Error : There is no endpoint existed in your config!! Please check your config file!");
}
this.ApplyMultiBehaviors(servicemodelSections); } /// <summary>
/// Check config file!
/// </summary>
/// <param name="configpath"></param>
/// <returns></returns>
private bool CheckConfigExist(string configpath)
{
if (string.IsNullOrEmpty(configpath)) return false;
if (!File.Exists(configpath)) return false;
return true;
} /// <summary>
/// Apply section info
/// </summary>
/// <param name="serviceFullName"></param>
/// <param name="servicemodelSections"></param>
/// <returns></returns>
private bool ApplySectionInfo(string serviceFullName, ServiceModelSectionGroup servicemodelSections)
{
// Check config sections (!including one section at least!)
if (servicemodelSections == null) return false;
// Service name can't be none!
if (string.IsNullOrEmpty(serviceFullName)) return false;
bool isElementExist = false;
foreach (ServiceElement element in servicemodelSections.Services.Services)
{
if (element.Name == serviceFullName)
{
// Find successfully & apply section info of config file
base.LoadConfigurationSection(element);
// Find service element successfully
isElementExist = true;
break;
}
}
return isElementExist;
} /// <summary>
/// Add behaviors
/// </summary>
/// <param name="servicemodelSections"></param>
/// <returns></returns>
private bool ApplyMultiBehaviors(ServiceModelSectionGroup servicemodelSections)
{
if (servicemodelSections == null) return false;
foreach (ServiceBehaviorElement element in servicemodelSections.Behaviors.ServiceBehaviors)
{
foreach (BehaviorExtensionElement behavior in element)
{
BehaviorExtensionElement behaviorEx = behavior;
object extention = behaviorEx.GetType().InvokeMember("CreateBehavior",
BindingFlags.InvokeMethod | BindingFlags.NonPublic | BindingFlags.Instance,
null,
behaviorEx,
null);
if (extention == null) continue;
IServiceBehavior isb = (IServiceBehavior)extention;
//if (base.Description.Behaviors.Contains(isb)) break;
bool isbehaviorExisted = false;
foreach (IServiceBehavior i in base.Description.Behaviors)
{
if (i.GetType().Name == isb.GetType().Name)
{
isbehaviorExisted = true;
break;
}
}
if (isbehaviorExisted) break;
base.Description.Behaviors.Add((IServiceBehavior)extention);
}
}
return true;
} }
像上面那样,我们就把配置文件移到了MyApp.config。如果是控制台程序类的WCF服务就可以像下面那样来启动:
using (MyServiceHost host=new MyServiceHost(typeof(Service1)))
{
//... do something
host.Open();
}
而对于宿主是IIS的WCF服务,我们还需要再重写ServiceHostFactory:
public class MyServiceHostFactory : ServiceHostFactory
{
protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses)
{
return new MyServiceHost(serviceType, baseAddresses);
}
}
然后在WCF服务的svc文件中,指定factory属性的值为我们重写的ServiceHostFactory:
<%@ ServiceHost Factory="WcfService1.MyServiceHostFactory" Language="C#" Debug="true" Service="WcfService1.Service1" CodeBehind="Service1.svc.cs" %>
WCF重写ServiceHost,实现独立配置文件的更多相关文章
- IOC容器Unity的使用及独立配置文件Unity.Config
[本段摘录自:IOC容器Unity 使用http://blog.csdn.net/gdjlc/article/details/8695266] 面向接口实现有很多好处,可以提供不同灵活的子类实现,增加 ...
- log4net保存到数据库系列二:独立配置文件中配置log4net
园子里面有很多关于log4net保存到数据库的帖子,但是要动手操作还是比较不易,从头开始学习log4net数据库日志一.WebConfig中配置log4net 一.WebConfig中配置log4ne ...
- 改进uwsgi启动脚本,使其支持多个独立配置文件
最近在研究flask,在架设运行环境的时候犯了难.因为我想把每个独立的应用像NGINX处理多个网站那样,每个应用单独一个配置文件.而网上流传的uwsgi启动脚本都只支持单个配置文件.虽然有文章说可以把 ...
- WCF 自托管、无配置文件实现jsonp(跨域)的访问
以下内容基于WCF4.0,本文将对比讨论配置文件方案和无配置文件方案的实现方式. WCF4.0加入了对RESTFU和标准终结点的支持,这为实现跨域提供了简单的方式. 一.有配置文件的情况: 首先我们先 ...
- Redis 哨兵节点之间相互自动发现机制(自动重写哨兵节点的配置文件)
Redis的哨兵机制中,如果是多哨兵模式,哨兵节点之间也是可以相互感知的,各种搜索之后出来的是千篇一律的一个基础配置文件,在配置当前哨兵节点的配置文件中,并没有配置其他哨兵节点的任何信息.如下是一个哨 ...
- log4net独立配置文件配置(winfrom)
log4net配置很多,具体配置步骤不细说,具体说出个人遇到的问题. 在winfrom和web应用程序中配置,在默认配置文件配置都没问题,因为EF也写在默认配置文件中,就会冲突解决办法就是将log4. ...
- WCF全面解析之三 使用配置文件启动WCF服务
知识:WCF地址.WCF绑定 Endpoint的配置 服务的三要素(ABC) A:Address 地址 有传输方式信息 B:Binding 怎么做(与地址的传输方式要匹配) C:Contract 做什 ...
- WCF的行为与异常-------配置文件说明
ServiceBehavior and OperationBehavior(这些都是应用在实现类上) http://msdn.microsoft.com/zh-cn/library/system.se ...
- [WCF REST] WebServiceHost 不依赖配置文件启动简单服务
最近用WPF启动 WCF REST 服务,发现app.config 配置好烦,简单一个exe 可以到处搬动,还非得带一个累赘配置,不小心丢了程序就跑不起来. 最后决定,砍去WCF配置项,用WebSer ...
随机推荐
- PHP无限极分类生成树方法,无限分级
你还在用浪费时间又浪费内存的递归遍历无限极分类吗,看了该篇文章,我觉得你应该换换了.这是我在OSChina上看到的一段非常精简的PHP无限极分类生成树方法,巧在引用,整理分享了. function g ...
- PostgreSQL中的时间操作总结
取当前日期的函数: (1) 取当前时间:select now() (2) 取当前时间的日期: select current_date (3) 取当前具体时间(不含日 ...
- js 判断鼠标滚轮方向
最近因为公司项目的要求,需要做页面的全屏滚动切换效果. 页面的切换,需要脚本监听鼠标滑轮的滚动事件,来判断页面是向上切换or向下切换. 这里的脚本很简单,我就直接贴出来吧. $('html').on( ...
- 序列化反序列化api(入门级)
定义: java序列化是指把Java对象转换为字节序列的过程:而Java反序列化是指把字节序列恢复为Java对象的过程. 为什么字符串通常也会进行序列化? 对象需要进行序列化的原因:保证对象的状态不变 ...
- 使用LIBSVM工具实现样本分类预测——MatLab
准备工作: https://www.csie.ntu.edu.tw/~cjlin/libsvm/,下载LIBSVM:(LIBSVM工具相较于MATLAB自带的工具:1).支持多分类及回归(‘-s 0’ ...
- CentOS6.3编译安装Memcached集群分布式缓存代理Magent-0.6出错汇总
参考文章:Memcached集群/分布式/高可用 及 Magent缓存代理搭建过程 详解,搭建Magent,在编译的过程中会出现很多错误: #编译安装安装magent到 /usr/local/mage ...
- memcache安装
windows下访问 http://pecl.php.net/package/memcache/3.0.8/windows 下载对应版本memcache的dll文件添加到php目录ext下 PHP.i ...
- SQL Server中解决死锁
SQL Server中解决死锁的新方法介绍 数据库操作的死锁是不可避免的,本文并不打算讨论死锁如何产生,重点在于解决死锁,通过SQL Server 2005, 现在似乎有了一种新的解决办法. 将下面的 ...
- Code First02---CodeFirst配置实体与数据库映射的两种方式
Code First有两种配置数据库映射的方式,一种是使用数据属性DataAnnotation,另一种是Fluent API. 这两种方式分别是什么呢?下面进行一一解释: DataAnnotation ...
- DateEdit和TimeEdit用法
DateEdit 控件默认情况下,显示的只有日期,没有时间.下面介绍2中日期和时间同时显示的方法: 1.Properties.VistaDisplayMode 为true, 2.Properties. ...