我想托管WCF服务,但我不想使用app.config
文件,但与此类似:
// 2nd Procedure:
// Use the binding in a service
// Create the Type instances for later use and the URI for
// the base address.
Type contractType = typeof(ICalculator);
Type serviceType = typeof(Calculator);
Uri baseAddress = new Uri("http://localhost:8036/SecuritySamples/");
// Create the ServiceHost and add an endpoint, then start
// the service.
ServiceHost myServiceHost = new ServiceHost(serviceType, baseAddress);
myServiceHost.AddServiceEndpoint(contractType, myBinding, "secureCalculator");
//enable metadata
ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
smb.HttpGetEnabled = true;
myServiceHost.Description.Behaviors.Add(smb);
myServiceHost.Open();
之后,我想添加Windows服务项目并托管我的服务。
我应该使用哪个项目?我不想要控制台或Winforms,我只想要Windows服务
我检查了Windows Service project
,我有这个主要的:
static void Main()
{
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new Service1()
};
ServiceBase.Run(ServicesToRun);
}
服务代码应该放在哪里?
您可以将第一个代码块中的代码放入的OnStart
函数中Service1
。
private _myServiceHost;
protected override void OnStart(string[] args)
{
if(_myServiceHost != null)
{
//Close the connection if the service was already opened.
_myServiceHost.Close();
}
// 2nd Procedure:
// Use the binding in a service
// Create the Type instances for later use and the URI for
// the base address.
Type contractType = typeof(ICalculator);
Type serviceType = typeof(Calculator);
Uri baseAddress = new Uri("http://localhost:8036/SecuritySamples/");
// Create the ServiceHost and add an endpoint, then start
// the service.
_myServiceHost = new ServiceHost(serviceType, baseAddress);
_myServiceHost.AddServiceEndpoint(contractType, myBinding, "secureCalculator");
//enable metadata
ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
smb.HttpGetEnabled = true;
_myServiceHost.Description.Behaviors.Add(smb);
_myServiceHost.Open();
}
//Adding a close on OnStop gives you a more graceful shutdown of your service, letting clients finish the work they are currently on
protected override void OnStop()
{
if(_myServiceHost != null)
{
_myServiceHost.Close();
_myServiceHost = null;
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句