【问题标题】:Can WCF self hosted applications create ServiceHosts automatically using the app.config?WCF 自托管应用程序可以使用 app.config 自动创建 ServiceHosts 吗?
【发布时间】:2010-09-18 02:49:52
【问题描述】:

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

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

是否有工厂或教程有人可以链接我,告诉我如何做到这一点? 谢谢

【问题讨论】:

    标签: wcf


    【解决方案1】:

    我不确定从配置中提取关联地址和合同是什么意思 - 这是自动完成的。配置文件中的服务部分会自动与 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();
                       }
                   }
               }
           }
       } 
    

    【讨论】:

    • 太棒了!那正是我所缺少的。我不确定如何遍历配置来实例化服务。抱歉,我的问题太含糊了。我不太确定如何表达它。
    猜你喜欢
    • 1970-01-01
    • 2017-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多