Search code examples
wcfwcf-hosting

Programmatically configure and host WCF Service in IIS


How can i programmatically configure and host WCF Service in IIS. I have created my WCF service example /WCFServices/Service1.svc". I want to programmatically configure and host this service in IIS. Can anyone help me on this?


Solution

  • The class you want is Microsoft.Web.Administration.ServerManager

    http://msdn.microsoft.com/en-us/library/microsoft.web.administration.servermanager(v=VS.90).aspx

    It has methods for manipulating most aspects of IIS, for example, adding application pools and applications. for example, this code configures a new IIS application

    //the name of the IIS AppPool you want to use for the application  - could be DefaultAppPool
    string appPoolName = "MyAppPool";
    
    //the name of the application (as it will appear in IIS manager)
    string name = "MyWCFService";
    
    //the physcial path of your application
    string physicalPath = "C:\\wwwroot\mywcfservice";
    
    
    using (ServerManager serverManager = new ServerManager())
        {
          Configuration config = serverManager.GetApplicationHostConfiguration();
          ConfigurationSection sitesSection = config.GetSection("system.applicationHost/sites");
          ConfigurationElementCollection sitesCollection = sitesSection.GetCollection();
          ConfigurationElement siteElement = sitesCollection[0]; 
          ConfigurationElementCollection siteCollection = siteElement.GetCollection();
          ConfigurationElement applicationElement = siteCollection.CreateElement("application");
          applicationElement["path"] = name;
          applicationElement["applicationPool"] = appPoolName;
          ConfigurationElementCollection applicationCollection = applicationElement.GetCollection();
          ConfigurationElement virtualDirectoryElement = applicationCollection.CreateElement("virtualDirectory");
          virtualDirectoryElement["path"] = @"/";
          virtualDirectoryElement["physicalPath"] = physicalPath;
          applicationCollection.Add(virtualDirectoryElement);
          siteCollection.Add(applicationElement);
          serverManager.CommitChanges();
        }
    

    In general, the calss is just a thin wrapper around the IIS config file. You can understand it by looking at your exisiting file, or even by looking at what you have to do in IIS Manager to configure the service manually, then translating that into the resulting configuration changes.

    You can do all (at least lots of) the the IIS configuration in this way (e.g. configure application throttling, enable authentication schemes etc.).

    The WCF part of the configuration is just normal WCF. you can do it either in code or in configuration.