2013-01-08 113 views
5

我做了以下如何將參數傳遞給ServiceHost的

//Define the service host 
     this._smeediPluginServiceHost = new ServiceHost(typeof(SmeediServiceHost), smeediServiceUri); 
     this._smeediPluginServiceHost.AddServiceEndpoint(typeof(ISmeediServiceHost), GetBinding(), smeediServiceUri); 
     SetupAndStartWebService(_smeediPluginServiceHost); 


    private void SetupAndStartWebService(ServiceHost serviceHost, ServiceDiscoveryBehavior serviceDiscoveryBehavior = null) 
    { 
     //Define service behaviours 
     ServiceMetadataBehavior serviceMetadataBehavior = new ServiceMetadataBehavior(); 
     serviceMetadataBehavior.HttpGetEnabled = true; 

     //Add the behaviours to the service 
     serviceHost.Description.Behaviors.Add(serviceMetadataBehavior); 

     if (serviceDiscoveryBehavior != null) 
      serviceHost.Description.Behaviors.Add(serviceDiscoveryBehavior); 

     serviceHost.Open(); 
    } 

我需要傳遞參數給服務,我無法弄清楚如何。我曾看過How do I pass values to the constructor on my wcf service?,但無法擺脫困境。謝謝

+0

你可以在服務本身使用ConfigurationManager.AppSettings []從app.config文件中讀取而不是傳遞給構造函數嗎? – TylerOhlsen

回答

17

如果我理解正確,你想傳遞參數給你的服務實現類的構造函數。你可以通過passing an instance of the service class to the ServiceHost constructor來代替它的類型。那就是:

// Create the service instance 
var instance = new SmeediServiceHost("some parameters"); 

// Define the service host using the above instance 
this._smeediPluginServiceHost = new ServiceHost(instance, smeediServiceUri); 

注意 - 使用這種方法意味着你正在使用的服務類的單一實例。如果您需要每個會話或每個請求新的實例,請考慮使用ServiceHostFactory,如this answer中所述。

+0

+1。作爲補充,有用的文章:[WCF Service Instancing](http://devproconnections.com/net-framework/wcf-service-instancing) – informatik01