gpt4 book ai didi

wcf - WCF 自托管应用程序可以使用 app.config 自动创建 ServiceHost 吗?

转载 作者:行者123 更新时间:2023-12-03 01:28:52 24 4
gpt4 key购买 nike

当我创建自托管 wcf 应用程序时,我为要公开的每个服务创建 ServiceHost 对象。然后它会查找 app.config(匹配服务器名称),然后提取关联的端点地址和合约。

有没有办法为 app.config 中列出的每个服务自动创建 ServiceHost。我想向 app.config 添加新服务并自动加载它们,而无需重新编译我的程序并使用我手动编码的过程来创建 ServiceHost 对象。

是否有人可以链接我的工厂或教程来向我展示如何做到这一点?谢谢

最佳答案

我不确定从配置中提取关联的地址和合约是什么意思 - 这是自动完成的。配置文件中的服务部分会自动与 ServiceHost 中托管的服务类型配对:

服务托管:

using (var host = new ServiceHost(typeof(MyNamespace.Service))
{
// no endpoint setting needed if configuration is correctly paired by the type name
host.Open()
}

服务配置:

<services>
<service name="MyNamespace.Service">
...
</service>
</service>

现在您唯一需要的就是自动处理 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();
}
}
}
}
}

关于wcf - WCF 自托管应用程序可以使用 app.config 自动创建 ServiceHost 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3740193/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com