Can WCF self hosted applications create ServiceHosts automatically using the app.config?
When I create a开发者_开发问答 self hosted wcf application, I create ServiceHost objects for each service I want to expose. It then looks in the app.config (matching up the server name), and then pulls the associated endpoint address and contract.
Is there a way to automatically create ServiceHosts for every service that is listed in the app.config. I would like to add new services to the app.config and have them loaded automatically without recompilng my program and using my manually coded process to create ServiceHost objects.
Is there a factory or a tutorial someone could link me that shows me how to do this? Thanks
I'm not sure what do you mean by pulling associated addresses and contracts from config - this is done automatically. Service section in configuration file is automatically paired with type of service hosted in 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 the only thing you need is to handle ServiceHost creation automatically. Here is my sample code to do it:
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();
}
}
}
}
}
精彩评论