Can standalone WCF applications automatically create ServiceHosts using app.config?

When I create a self-contained wcf application, I create ServiceHost objects for every service I want to open. Then it looks at the app.config file (server name mapping), and then it pulls out the corresponding endpoint address and is compressed.

Is there a way to automatically create ServiceHosts for each service specified in app.config. I would like to add new services to app.config and load them automatically without recompiling my program and using my manually encoded process to create ServiceHost objects.

Is there a factory or tutorial that could connect me that shows me how to do this? Thanks

+10
wcf
Sep 18 2018-10-18T00:
source share
1 answer

I'm not sure what you mean by pulling the associated addresses and contracts from config - this is done automatically. The service section in the configuration file is automatically connected to the type of service hosted by ServiceHost:

Service hosting:

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

Service Configuration:

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

Now you only need to automatically process the creation of the ServiceHost. Here is my sample code:

  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(); } } } } } 
+19
Sep 18 '10 at 9:20
source share
— -



All Articles