# .NET and More > WPF, WCF, WF >  [RESOLVED] running a wcf process inside a windows service.

## Bill Crawley

Hi All,

My app started off as a standard web app, but becuase the client is really initiating a batch process that potentially may run for a long time, I pulled the long running process out and made it a WCF Service Library. However, it occured to me that the app would still suffer time out issues due to IIS recycling etc. SO to negate this I've attempted to write a windows service that wraps the WCF Process. I've followed many examples from the web on setting the Windows service up, but when I try to run the service it stops straight away. 

In the Windows Service in the Default program.cs file, I've not made any changes to the default code.:



```
static void Main()
        {
            ServiceBase[] ServicesToRun;
            ServicesToRun = new ServiceBase[] 
			{ 
				new IRSBorderauxService() 
			};
            ServiceBase.Run(ServicesToRun);
        }
```

I've made a reference to the WCF dll that was generated from the build of my WCF Project.

in the IRSBorderauxService I have made a reference to the service and declared a ServiceHost.



```
using wcfBorderauxIRSService;

namespace IRSBorderauxService
{
    public partial class IRSBorderauxService : ServiceBase
    {
        ServiceHost sHost;
        public IRSBorderauxService()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            sHost = new ServiceHost(typeof(wcfBorderauxIRSService.IRSService));
            sHost.Open();
                      
        }

        protected override void OnStop()
        {
            sHost.Close();
        }
    }
}
```

I have also created an App.config file based on the WCF projects app.config.
I have also introduced a project listener and against the ServiceInstaller have set the Start Type to Automatic and set the serviceName.

If I attempt to step the code, it gets to the last line of program.cs Main 



```
ServiceBase.Run(ServicesToRun);
```

and error's with : Cannot start service from the command line or debugger. A Windows Service must first be installed (using installutil.exe)....

I Created a setup project in the solution and run the install, I can see the Machines Services from the control panel.

Can anybody tell me what I have missed.

----------


## Lightning

Can you start the service from the services-control-panel?
How you configure the serivce, eg the endpoint, do you use a config file?

O and I think there are not many reasons to NOT host the service in the IIS, there are some valid cases but IIS handles much things for you.

----------


## Bill Crawley

THis is essentially my config file



```
	<system.serviceModel>
		<bindings>
			<wsHttpBinding>
				<binding name="WSHttpBinding_IRS" closeTimeout="00:01:00" openTimeout="00:01:00"
				  receiveTimeout="00:10:00" sendTimeout="00:01:00" bypassProxyOnLocal="false"
				  transactionFlow="false" hostNameComparisonMode="StrongWildcard"
				  maxBufferPoolSize="524288" maxReceivedMessageSize="65536" messageEncoding="Text"
				  textEncoding="utf-8" useDefaultWebProxy="true" allowCookies="false">
					<readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
					  maxBytesPerRead="4096" maxNameTableCharCount="16384" />
					<reliableSession ordered="true" inactivityTimeout="00:10:00"
					  enabled="false" />
					<security mode="Message">
						<transport clientCredentialType="Windows" proxyCredentialType="None"
						  realm="" />
						<message clientCredentialType="Windows" negotiateServiceCredential="true"
						  algorithmSuite="Default" />
					</security>
				</binding>
			</wsHttpBinding>
		</bindings>
		<client>
			<endpoint address="http://localhost:8730/Design_Time_Addresses/wcfBorderauxIRSService/Service1/"
			  binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_IRS"
			  contract="IRSBorderauxService.IRS" name="WSHttpBinding_IRS">
				<identity>
					<dns value="localhost" />
				</identity>
			</endpoint>
		</client>
		<diagnostics>
			<messageLogging logMalformedMessages="true" logMessagesAtTransportLevel="true" />
		</diagnostics>
		<serviceHostingEnvironment aspNetCompatibilityEnabled="false" />
		<services>
			<service name="wcfBorderauxIRSService.IRSService">
				<host>
					<baseAddresses>
						<add baseAddress="http://localhost:8730/Design_Time_Addresses/wcfBorderauxIRSService/Service1/" />
					</baseAddresses>
				</host>
				<endpoint address="" binding="wsHttpBinding"
				  contract="wcfBorderauxIRSService.IRS">
					<identity>
						<dns value="localhost" />
					</identity>
				</endpoint>
				<endpoint address="mex" binding="mexHttpBinding"
				  contract="IMetadataExchange" />

			</service>
		</services>
		<behaviors>
			<serviceBehaviors>
				<behavior>
					<!-- To avoid disclosing metadata information, 
          set the value below to false and remove the metadata endpoint above before deployment -->
					<serviceMetadata httpGetEnabled="True"/>
					<!-- To receive exception details in faults for debugging purposes, 
          set the value below to true.  Set to false before deployment 
          to avoid disclosing exception information -->
					<serviceDebug includeExceptionDetailInFaults="False" />
				</behavior>
			</serviceBehaviors>
		</behaviors>
	</system.serviceModel>
```

From the services control panel it starts and stops straight away.

I can say that I'm confident that I have built the WCF Service correctly as  when I test locally and invoke a method I can see the effect in my backend database.

----------


## Bill Crawley

Ok,

I've had some success, but not quite out of the woods yet  :Smilie: .

I have now proved that my WCF Service runs correctly when tested on it's own. I've now managed to host the WCF Service in a windows Service. When I go to Services via control panel I can see my service and I can Start the service without it stopping straight away (it will now stop when I tell it to stop).

So now with all that done. The final stage is to plug the windows service into my asp.net (4.0) application. When I installed the windows service, it installed to a directory in my C:\Program Files Directory. in my installed directory there is a dependency DLL for the wcfService called wcfBorderauxIRSService.dll there is an XML file calles IRSBorderauxService.exe and a windows program called IRSBorderauxService.

In My Web App I made a reference to the IRSBorderauxService (windows App). But I seem not to be able to get to any methods in it. So how do I use the windows service in my app.

----------


## Bill Crawley

Because I want to run the service outside IIS, I re-wrote the app.config file to use tcpIp.



```
		<bindings>
			<netTcpBinding>
				<binding name="NetWcfTcpBinding" receiveTimeout="24:00:00">
					<reliableSession ordered="false" inactivityTimeout="00:30:00"/>
				</binding>
			</netTcpBinding>
		</bindings>
		<services>
			<service name="wcfBorderauxIRSService.IRSService" behaviorConfiguration="IRSBehaviour">
				<host>
					<baseAddresses>
						<add baseAddress="net.tcp://localhost:9999/wcfBorderauxIRSService/Service1/"/>
					</baseAddresses>
				</host>
				<endpoint name ="NetTcpEndPoint"
						  address =""
						  binding ="netTcpBinding"
						  contract ="wcfBorderauxIRSService.IRS"
						  bindingConfiguration="NetWcfTcpBinding">
				</endpoint>
				<endpoint name="NetTcpMetadataPoint"
						  address="mex"
						  binding="mexTcpBinding"
						  contract="IMetadataExchange"/>
				</service>
		</services>
		<behaviors>
			<serviceBehaviors>
				<behavior name="IRSBehaviour">
					<!-- To avoid disclosing metadata information, 
          set the value below to false and remove the metadata endpoint above before deployment -->
					<serviceMetadata httpGetEnabled="False"/>
					<!-- To receive exception details in faults for debugging purposes, 
          set the value below to true.  Set to false before deployment 
          to avoid disclosing exception information -->
					<serviceDebug includeExceptionDetailInFaults="False" />
				</behavior>
			</serviceBehaviors>
		</behaviors>
```

Then in my client code I attempt to add a servvice reference:


```
net.tcp://localhost:9999/wcfBorderauxIRSService/Service1/
```

I recive the following error adding the reference:



```
Metadata contains a reference that cannot be resolved: 'net.tcp://localhost:9999/wcfBorderauxIRSService/Service1/'.
Could not connect to net.tcp://localhost:9999/wcfBorderauxIRSService/Service1/. The connection attempt lasted for a time span of 00:00:01.0169770. TCP error code 10061: No connection could be made because the target machine actively refused it 127.0.0.1:9999. 
No connection could be made because the target machine actively refused it 127.0.0.1:9999
If the service is defined in the current solution, try building the solution and adding the service reference again.
```

In my windows service, because I am using tcp I have set the account type of the serviceProcessInstaller to NetWorkService as opposed to LocalService that I had initially.

----------

