Zom*_*eep 16 .net configuration wcf app-config
我有一个特定的要求,即从主app.config文件中删除所有客户端WCF配置(<system.serviceModel>),并将其删除到单独的XML文件中.我希望看到的行为类似于使用File =""指令在appSettings部分中提供的行为.事实上,我希望能够为每个消费的服务指定一个单独的文件...
我知道我可以构建一个自定义的ChannelBuilder工厂,它从XML文件(或其中一系列文件)中读取配置数据,但我更愿意仍然让客户端"自动发现"配置数据.
一些基本的谷歌搜索似乎暗示这是不可能的,但我想从SO获得视图 - 这里有人知道我无法找到的东西吗?:)
编辑::
蒂姆·斯科特和davogones都与一个可能的建议上来了,但一个依赖于分裂system.serviceModel节的组成部分出单独的文件.虽然这并不完全符合我要找的(我想定义每个服务及其相关的元素谨慎,每一个服务文件),它是一个选项.我会调查并让你知道我的想法.
小智 6
using System;
using System.Configuration;
using System.IO;
using System.ServiceModel;
using System.ServiceModel.Configuration;
namespace ConsoleHost
{
public class CustomServiceHost : ServiceHost
{
public CustomServiceHost(string customConfigPath, Type serviceType,
params Uri[] baseAddresses)
{
CustomConfigPath = customConfigPath;
var collection = new UriSchemeKeyedCollection(baseAddresses);
InitializeDescription(serviceType, collection);
}
public string CustomConfigPath { get; private set; }
protected override void ApplyConfiguration()
{
if (string.IsNullOrEmpty(CustomConfigPath) ||
!File.Exists(CustomConfigPath))
{
base.ApplyConfiguration();
}
else
{
LoadConfigFromCustomLocation(CustomConfigPath);
}
}
void LoadConfigFromCustomLocation(string configFilename)
{
var filemap = new ExeConfigurationFileMap
{
ExeConfigFilename = configFilename
};
Configuration config = ConfigurationManager.
OpenMappedExeConfiguration(filemap, ConfigurationUserLevel.None);
var serviceModel = ServiceModelSectionGroup.GetSectionGroup(config);
bool loaded = false;
foreach (ServiceElement se in serviceModel.Services.Services)
{
if (se.Name == Description.ConfigurationName)
{
LoadConfigurationSection(se);
loaded = true;
break;
}
}
if (!loaded)
throw new ArgumentException("ServiceElement doesn't exist");
}
}
}
Run Code Online (Sandbox Code Playgroud)
在这个类之后,只需使用它,就像通常用它来初始化服务主机一样
myServiceHost = new CustomServiceHost(ConfigFileName,typeof(QueryTree));
myServiceHost.Open();
我倾向于以编程方式配置我的所有服务设置.
我的客户并不是理解XML的类型,并且让我让配置文件更像旧的INI风格.
这很容易做到(不包括INI文件代码):
// create the URI which is used as the service endpoint
Uri tcpBaseAddress = new Uri(
string.Format("net.tcp://{0}:{1}",
LocalIPAddress.ToString(), GeneralPortNumber));
// create the net.tcp binding for the service endpoint
NetTcpBinding ntcBinding = new NetTcpBinding();
ntcBinding.Security.Mode = SecurityMode.None;
System.ServiceModel.Channels.Binding tcpBinding = ntcBinding;
// create the service host and add the endpoint
Host = new ServiceHost(typeof(WordWarService), tcpBaseAddress);
Run Code Online (Sandbox Code Playgroud)
由于我们可以以编程方式配置主机(和客户端),因此没有任何东西阻止您以您选择的任何方式提供设置(数据库,xml,疯狂文本文件等).