当我创建一个自托管的wcf应用程序时,我为每个要公开的服务创建ServiceHost对象.然后它在app.config(匹配服务器名称)中查找,然后提取关联的端点地址和合同.
有没有办法为app.config中列出的每个服务自动创建ServiceHosts.我想向app.config添加新服务并自动加载它们,而无需重新编译我的程序并使用我的手动编码过程来创建ServiceHost对象.
是否有工厂或教程可以链接我,告诉我如何做到这一点?谢谢
Lad*_*nka 19
我不确定你从配置中提取相关地址和合同是什么意思 - 这是自动完成的.配置文件中的服务部分自动与ServiceHost中托管的服务类型配对:
服务托管:
using (var host = new ServiceHost(typeof(MyNamespace.Service))
{
// no endpoint setting needed if configuration is correctly paired by the type name
host.Open()
}
Run Code Online (Sandbox Code Playgroud)
服务配置:
<services>
<service name="MyNamespace.Service">
...
</service>
</service>
Run Code Online (Sandbox Code Playgroud)
现在,您唯一需要的是自动处理ServiceHost创建.这是我的示例代码:
class Program
{
static void Main(string[] args)
{
List<ServiceHost> hosts = new List<ServiceHost>();
try
{
var section = ConfigurationManager.GetSection("system.serviceModel/services") as ServicesSection;
if (section != null)
{
foreach (ServiceElement element in section.Services)
{
var serviceType = Type.GetType(element.Name);
var host = new ServiceHost(serviceType);
hosts.Add(host);
host.Open();
}
}
Console.ReadLine();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
Console.ReadLine();
}
finally
{
foreach (ServiceHost host in hosts)
{
if (host.State == CommunicationState.Opened)
{
host.Close();
}
else
{
host.Abort();
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)