我知道这已经很旧了,但从未标记为已回答,所以我想我应该尝试一下。如果我明白你想要什么,你可以使用自定义 ServiceHostFactory 来完成。
关于这个的好帖子here http://blogs.msdn.com/dotnetinterop/archive/2008/09/22/custom-service-config-file-for-a-wcf-service-hosted-in-iis.aspx.
您可以像这样设置自定义服务 HostFactory:
<%@ ServiceHost
Language="C#"
Debug="true"
Service="Ionic.Samples.Webservices.Sep20.CustomConfigService"
Factory="Ionic.ServiceModel.ServiceHostFactory"%>
然后,在 ServiceHostFactory 中,您可以重写名为 ApplyConfiguration 的方法。通常,对于 IIS 中托管的 WCF 应用程序,WCF 会自动在 web.config 中查找配置。在此示例中,我们重写该行为以首先查找以 WCF 服务描述命名的配置文件。
protected override void ApplyConfiguration()
{
// generate the name of the custom configFile, from the service name:
string configFilename = System.IO.Path.Combine ( physicalPath,
String.Format("{0}.config", this.Description.Name));
if (string.IsNullOrEmpty(configFilename) || !System.IO.File.Exists(configFilename))
base.ApplyConfiguration();
else
LoadConfigFromCustomLocation(configFilename);
}
您可以将其替换为“任何内容” - 例如,在数据库表中查找配置。
还有一些方法可以完成这个难题。
private string _physicalPath = null;
private string physicalPath
{
get
{
if (_physicalPath == null)
{
// if hosted in IIS
_physicalPath = System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath;
if (String.IsNullOrEmpty(_physicalPath))
{
// for hosting outside of IIS
_physicalPath= System.IO.Directory.GetCurrentDirectory();
}
}
return _physicalPath;
}
}
private void LoadConfigFromCustomLocation(string configFilename)
{
var filemap = new System.Configuration.ExeConfigurationFileMap();
filemap.ExeConfigFilename = configFilename;
System.Configuration.Configuration config =
System.Configuration.ConfigurationManager.OpenMappedExeConfiguration
(filemap,
System.Configuration.ConfigurationUserLevel.None);
var serviceModel = System.ServiceModel.Configuration.ServiceModelSectionGroup.GetSectionGroup(config);
bool loaded= false;
foreach (System.ServiceModel.Configuration.ServiceElement se in serviceModel.Services.Services)
{
if(!loaded)
if (se.Name == this.Description.ConfigurationName)
{
base.LoadConfigurationSection(se);
loaded= true;
}
}
if (!loaded)
throw new ArgumentException("ServiceElement doesn't exist");
}