如何将参数传递给ServiceHost的
问题描述:
我做了以下如何将参数传递给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?,但无法摆脱困境。谢谢
答
如果我理解正确,你想传递参数给你的服务实现类的构造函数。你可以通过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
你可以在服务本身使用ConfigurationManager.AppSettings []从app.config文件中读取而不是传递给构造函数吗? – TylerOhlsen