<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>asp net core windows service &#8211; ASP.NET Hosting Reviews and Guides</title>
	<atom:link href="https://topreviewhostingasp.net/tag/asp-net-core-windows-service/feed/" rel="self" type="application/rss+xml" />
	<link>https://topreviewhostingasp.net</link>
	<description>ASP.NET Hosting &#124; Reviews &#124; Tips &#38; Tutorial</description>
	<lastBuildDate>Thu, 04 Aug 2022 06:42:13 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	

<image>
	<url>https://topreviewhostingasp.net/wp-content/uploads/2017/01/cropped-trhaico-32x32.png</url>
	<title>asp net core windows service &#8211; ASP.NET Hosting Reviews and Guides</title>
	<link>https://topreviewhostingasp.net</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>How to Host ASP.NET Core Web Application in Windows Service</title>
		<link>https://topreviewhostingasp.net/how-to-host-asp-net-core-web-application-in-windows-service/</link>
					<comments>https://topreviewhostingasp.net/how-to-host-asp-net-core-web-application-in-windows-service/#respond</comments>
		
		<dc:creator><![CDATA[Jacques Hunt]]></dc:creator>
		<pubDate>Thu, 04 Aug 2022 06:38:53 +0000</pubDate>
				<category><![CDATA[Hosting Tips]]></category>
		<category><![CDATA[asp net]]></category>
		<category><![CDATA[asp net core]]></category>
		<category><![CDATA[asp net core hosting]]></category>
		<category><![CDATA[asp net core tips]]></category>
		<category><![CDATA[asp net core tutorial]]></category>
		<category><![CDATA[asp net core windows service]]></category>
		<category><![CDATA[asp net tips]]></category>
		<guid isPermaLink="false">https://topreviewhostingasp.net/?p=3101</guid>

					<description><![CDATA[Did you know that we can host ASP.NET service on Windows with Windows Service without using IIS? The benefit of hosting on Windows Service is that the application will automatically restart after the server reboot. This functionality is implemented using a Worker Service Template that becomes the initial point for writing and building long-running service [&#8230;]]]></description>
										<content:encoded><![CDATA[
<p>Did you know that we can host ASP.NET service on Windows with Windows Service without using IIS? The benefit of hosting on Windows Service is that the application will automatically restart after the server reboot.</p>



<p>This functionality is implemented using a Worker Service Template that becomes the initial point for writing and building long-running service applications. We are focusing on a solution without the IIS because the same may not be available at all times.</p>



<p>Even in the situations where you have IIS already set up, it may not host .NET Core applications, let alone ASP.NET Core. Hence, to host them, you need to understand the implementation of the .NET Core web application in Visual Studio.</p>



<h2 class="wp-block-heading"><strong>Why Use a Web App as a Windows Service?</strong></h2>



<p>In situations where you want to host .NET Core applications without IIS, we can work with self-contained deployment. Here, the application basically runs as a .exe file.</p>



<p>Follow these steps to set up a hosting environment for ASP.NET 3.1 in Windows Service.</p>



<h3 class="wp-block-heading"><strong>1. Create new ASP.NET Core 3.1 Application in Visual Studio</strong></h3>



<p>Create a new project in VS2019 .NetCore web application. Specify version 3.1 as you create a new project in the folder (follow the screenshot).</p>



<div class="wp-block-image">
<figure class="aligncenter size-large"><img fetchpriority="high" decoding="async" width="543" height="307" class="wp-image-3102 aligncenter" src="https://topreviewhostingasp.net/wp-content/uploads/2022/08/new-project.png" alt="" srcset="https://topreviewhostingasp.net/wp-content/uploads/2022/08/new-project.png 543w, https://topreviewhostingasp.net/wp-content/uploads/2022/08/new-project-300x170.png 300w, https://topreviewhostingasp.net/wp-content/uploads/2022/08/new-project-50x28.png 50w" sizes="(max-width: 543px) 100vw, 543px" /></figure>
</div>



<h3 class="wp-block-heading"><strong>2. Running an ASP.Net Core application as a Windows Service</strong></h3>



<p>Following the first step, specify a runtime for the application. ASP.NET Core also supports operating systems where Windows Services don’t run.</p>



<p>For this, we must modify the project file. To modify the project file, double click on the Project name and add the following two lines as per the screenshot.</p>



<div class="wp-block-image">
<figure class="aligncenter size-large"><img decoding="async" width="779" height="316" class="wp-image-3103 aligncenter" src="https://topreviewhostingasp.net/wp-content/uploads/2022/08/Running-an-ASP.Net-Core-1.png" alt="" srcset="https://topreviewhostingasp.net/wp-content/uploads/2022/08/Running-an-ASP.Net-Core-1.png 779w, https://topreviewhostingasp.net/wp-content/uploads/2022/08/Running-an-ASP.Net-Core-1-300x122.png 300w, https://topreviewhostingasp.net/wp-content/uploads/2022/08/Running-an-ASP.Net-Core-1-768x312.png 768w, https://topreviewhostingasp.net/wp-content/uploads/2022/08/Running-an-ASP.Net-Core-1-50x20.png 50w" sizes="(max-width: 779px) 100vw, 779px" /></figure>
</div>



<p>Add a reference using NuGet package <strong>Microsoft.ASPNetCore.Hosting.WindowsServices</strong> and <strong>Newtonsoft.json</strong>.</p>



<p>This Package has everything needed to run an ASP.Net Core application as a Window service.</p>



<div class="wp-block-image">
<figure class="aligncenter size-large"><img decoding="async" width="709" height="249" class="wp-image-3104 aligncenter" src="https://topreviewhostingasp.net/wp-content/uploads/2022/08/NuGet-package-1.png" alt="" srcset="https://topreviewhostingasp.net/wp-content/uploads/2022/08/NuGet-package-1.png 709w, https://topreviewhostingasp.net/wp-content/uploads/2022/08/NuGet-package-1-300x105.png 300w, https://topreviewhostingasp.net/wp-content/uploads/2022/08/NuGet-package-1-50x18.png 50w" sizes="(max-width: 709px) 100vw, 709px" /></figure>
</div>



<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="718" height="243" class="wp-image-3105 aligncenter" src="https://topreviewhostingasp.net/wp-content/uploads/2022/08/NuGet-package-2.png" alt="" srcset="https://topreviewhostingasp.net/wp-content/uploads/2022/08/NuGet-package-2.png 718w, https://topreviewhostingasp.net/wp-content/uploads/2022/08/NuGet-package-2-300x102.png 300w, https://topreviewhostingasp.net/wp-content/uploads/2022/08/NuGet-package-2-50x17.png 50w" sizes="(max-width: 718px) 100vw, 718px" /></figure>
</div>



<p>Now, run the application as Windows Service and configure it in the Program.cs file. In case you want to run an application as IIS Express, then there is no need to change any configuration setting, and we can directly run an application as IIS Express.</p>



<p>We can specify a different port in the <strong>appsettings.json</strong> and <strong>appsettings.Devlopment.json</strong> file to run an application on this port directly using the Windows service.</p>



<p>Specify Port no 5009.</p>



<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://www.asphostportal.com" target="_blank" rel="noopener"><img loading="lazy" decoding="async" width="300" height="271" class="wp-image-2584 aligncenter" src="https://topreviewhostingasp.net/wp-content/uploads/2018/11/ahp-banner-aspnet-01.png" alt="" srcset="https://topreviewhostingasp.net/wp-content/uploads/2018/11/ahp-banner-aspnet-01.png 300w, https://topreviewhostingasp.net/wp-content/uploads/2018/11/ahp-banner-aspnet-01-50x45.png 50w" sizes="(max-width: 300px) 100vw, 300px" /></a></figure>
</div>



<p><strong><u>appsettings.json File:</u></strong></p>



<pre class="wp-block-code"><code>{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
	}
  },
"AllowedHosts": "*",
"ServicePort" :  5009
}
 appsettings.Devlopment.json file:
{
"DetailedErrors": true,
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
	}
  },
"ServicePort": 5009</code></pre>



<p>Moving on, to specify our <strong>appsettings.json</strong> file as Configuration path in <strong>Program.cs</strong> file to let the application read that path and run on that port. See the screenshots below.</p>



<p><strong>Program.csFile:</strong></p>



<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="944" height="590" class="wp-image-3106 aligncenter" src="https://topreviewhostingasp.net/wp-content/uploads/2022/08/Program.csFile.png" alt="" srcset="https://topreviewhostingasp.net/wp-content/uploads/2022/08/Program.csFile.png 944w, https://topreviewhostingasp.net/wp-content/uploads/2022/08/Program.csFile-300x188.png 300w, https://topreviewhostingasp.net/wp-content/uploads/2022/08/Program.csFile-768x480.png 768w, https://topreviewhostingasp.net/wp-content/uploads/2022/08/Program.csFile-50x31.png 50w" sizes="(max-width: 944px) 100vw, 944px" /></figure>
</div>



<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="944" height="484" class="wp-image-3107 aligncenter" src="https://topreviewhostingasp.net/wp-content/uploads/2022/08/Program.csFile-2.png" alt="" srcset="https://topreviewhostingasp.net/wp-content/uploads/2022/08/Program.csFile-2.png 944w, https://topreviewhostingasp.net/wp-content/uploads/2022/08/Program.csFile-2-300x154.png 300w, https://topreviewhostingasp.net/wp-content/uploads/2022/08/Program.csFile-2-768x394.png 768w, https://topreviewhostingasp.net/wp-content/uploads/2022/08/Program.csFile-2-50x26.png 50w" sizes="(max-width: 944px) 100vw, 944px" /></figure>
</div>



<h3 class="wp-block-heading"><strong>3.</strong> <strong>Build the application and Publish the code</strong></h3>



<p>With the above-given configuration completed in the <strong>Program.cs</strong> file start building the application, followed by publishing the code in the folder.</p>



<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="944" height="489" class="wp-image-3108 aligncenter" src="https://topreviewhostingasp.net/wp-content/uploads/2022/08/Build-the-application.png" alt="" srcset="https://topreviewhostingasp.net/wp-content/uploads/2022/08/Build-the-application.png 944w, https://topreviewhostingasp.net/wp-content/uploads/2022/08/Build-the-application-300x155.png 300w, https://topreviewhostingasp.net/wp-content/uploads/2022/08/Build-the-application-768x398.png 768w, https://topreviewhostingasp.net/wp-content/uploads/2022/08/Build-the-application-50x26.png 50w" sizes="(max-width: 944px) 100vw, 944px" /></figure>
</div>



<h3 class="wp-block-heading"><strong>4. Making the application Run as WindowsService</strong></h3>



<p>To make the application run as a Windows service follow these steps;</p>



<ul>
<li>Open the Command line with administrative Permission.</li>
<li>Register the application as a Windows service using this command (<strong>space after “binPath=” is mandatory</strong>)</li>
</ul>



<p><strong>Create windows service using the following command</strong>:</p>



<p><strong>sc create AspNetCoreWindowsServicebinPath = “path to my publish folder application exe –service”</strong></p>



<p>In the example above, we have taken <strong>AspNetCoreWindowsService</strong> as the name; you can use any name you want to keep. Also, <strong>–service</strong> is an argument name that we pass in <strong>Program.cs</strong> file.</p>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="862" height="466" class="wp-image-3109 aligncenter" src="https://topreviewhostingasp.net/wp-content/uploads/2022/08/cmd-to-Create-windows-service.png" alt="" srcset="https://topreviewhostingasp.net/wp-content/uploads/2022/08/cmd-to-Create-windows-service.png 862w, https://topreviewhostingasp.net/wp-content/uploads/2022/08/cmd-to-Create-windows-service-300x162.png 300w, https://topreviewhostingasp.net/wp-content/uploads/2022/08/cmd-to-Create-windows-service-768x415.png 768w, https://topreviewhostingasp.net/wp-content/uploads/2022/08/cmd-to-Create-windows-service-50x27.png 50w" sizes="(max-width: 862px) 100vw, 862px" /></figure>



<p>Nest, open the <strong>services.msc</strong> and see your hosted Windows service with the name <strong>AspNetCoreWindowsService</strong> to start the service.</p>



<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="879" height="490" class="wp-image-3110 aligncenter" src="https://topreviewhostingasp.net/wp-content/uploads/2022/08/AspNetCoreWindowsService.png" alt="" srcset="https://topreviewhostingasp.net/wp-content/uploads/2022/08/AspNetCoreWindowsService.png 879w, https://topreviewhostingasp.net/wp-content/uploads/2022/08/AspNetCoreWindowsService-300x167.png 300w, https://topreviewhostingasp.net/wp-content/uploads/2022/08/AspNetCoreWindowsService-768x428.png 768w, https://topreviewhostingasp.net/wp-content/uploads/2022/08/AspNetCoreWindowsService-50x28.png 50w" sizes="(max-width: 879px) 100vw, 879px" /></figure>
</div>



<p>When the service starts, open the browser and navigate to <a href="http://localhost:50009/"><strong>http://localhost:50009</strong></a> to see the web application is running. If you would remember, we had set port 5009 in the earlier steps of ASP.NET core web application development. Specifically, look for the part where we had specified it in the <strong>appsetting.json</strong> file as mentioned above.</p>



<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="840" height="494" class="wp-image-3111 aligncenter" src="https://topreviewhostingasp.net/wp-content/uploads/2022/08/Welcome.png" alt="" srcset="https://topreviewhostingasp.net/wp-content/uploads/2022/08/Welcome.png 840w, https://topreviewhostingasp.net/wp-content/uploads/2022/08/Welcome-300x176.png 300w, https://topreviewhostingasp.net/wp-content/uploads/2022/08/Welcome-768x452.png 768w, https://topreviewhostingasp.net/wp-content/uploads/2022/08/Welcome-50x29.png 50w" sizes="(max-width: 840px) 100vw, 840px" /></figure>
</div>



<p>Delete windows service using the following command:</p>



<p>Stop the existing running instance before releasing the new version of the service. Once done, write the following command.</p>



<p><strong>scdeleteAspNetCoreWindowsService</strong></p>



<p>Again, <strong>AspNetCoreWindowsService i</strong>s the windows service name that we have set to give you an example.</p>



<h2 class="wp-block-heading">Conclusion</h2>



<p>This article takes you through the steps to set up a hosting environment for <strong>ASP.NET Core 3.1 web application development in Windows Service</strong>. Although the process is simple enough to understand, we at <strong>DEV IT</strong> have understood the nuances of the same along with knowing everything about <strong>agile development practices</strong>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://topreviewhostingasp.net/how-to-host-asp-net-core-web-application-in-windows-service/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>How to Host ASP.NET Core in Window Service</title>
		<link>https://topreviewhostingasp.net/how-to-host-asp-net-core-in-window-service/</link>
					<comments>https://topreviewhostingasp.net/how-to-host-asp-net-core-in-window-service/#respond</comments>
		
		<dc:creator><![CDATA[Jacques Hunt]]></dc:creator>
		<pubDate>Wed, 30 Mar 2022 05:29:33 +0000</pubDate>
				<category><![CDATA[Hosting Tips]]></category>
		<category><![CDATA[asp net core]]></category>
		<category><![CDATA[asp net core tips]]></category>
		<category><![CDATA[asp net core tutorial]]></category>
		<category><![CDATA[asp net core windows service]]></category>
		<category><![CDATA[host asp net]]></category>
		<category><![CDATA[host asp net core]]></category>
		<category><![CDATA[windows service]]></category>
		<guid isPermaLink="false">https://topreviewhostingasp.net/?p=3025</guid>

					<description><![CDATA[Did you know that we can host ASP.NET service on Windows with Windows Service without using IIS? The benefit of hosting on Windows Service is that the application will automatically restart after the server reboot. This functionality is implemented using a Worker Service Template that becomes the initial point for writing and building long-running service [&#8230;]]]></description>
										<content:encoded><![CDATA[
<p>Did you know that we can host ASP.NET service on Windows with Windows Service without using IIS? The benefit of hosting on Windows Service is that the application will automatically restart after the server reboot.</p>



<p>This functionality is implemented using a Worker Service Template that becomes the initial point for writing and building long-running service applications. We are focusing on a solution without the IIS because the same may not be available at all times.</p>



<p>Even in the situations where you have IIS already set up, it may not host .NET Core applications, let alone ASP.NET Core. Hence, to host them, you need to understand the implementation of the .NET Core web application in Visual Studio.</p>



<h2 class="wp-block-heading"><strong>Why Use a Web App as a Windows Service?</strong></h2>



<p>In situations where you want to host .NET Core applications without IIS, we can work with self-contained deployment. Here, the application basically runs as a .exe file.</p>



<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://www.asphostportal.com" target="_blank" rel="noopener"><img loading="lazy" decoding="async" width="300" height="271" class="wp-image-2584 aligncenter" src="https://topreviewhostingasp.net/wp-content/uploads/2018/11/ahp-banner-aspnet-01.png" alt="" srcset="https://topreviewhostingasp.net/wp-content/uploads/2018/11/ahp-banner-aspnet-01.png 300w, https://topreviewhostingasp.net/wp-content/uploads/2018/11/ahp-banner-aspnet-01-50x45.png 50w" sizes="(max-width: 300px) 100vw, 300px" /></a></figure>
</div>



<p>Follow these steps to set up a hosting environment for ASP.NET 3.1 in Windows Service.</p>



<h3 class="wp-block-heading"><strong>1. Create new ASP.NET Core 3.1 Application in Visual Studio</strong></h3>



<p>Create a new project in VS2019 .NetCore web application. Specify version 3.1 as you create a new project in the folder (follow the screenshot).</p>



<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="543" height="307" class="wp-image-3026 aligncenter" src="https://topreviewhostingasp.net/wp-content/uploads/2022/03/aspnetcore-1.png" alt="" srcset="https://topreviewhostingasp.net/wp-content/uploads/2022/03/aspnetcore-1.png 543w, https://topreviewhostingasp.net/wp-content/uploads/2022/03/aspnetcore-1-300x170.png 300w, https://topreviewhostingasp.net/wp-content/uploads/2022/03/aspnetcore-1-50x28.png 50w" sizes="(max-width: 543px) 100vw, 543px" /></figure>
</div>



<h3 class="wp-block-heading"><strong>2. Running an ASP.Net Core application as a Windows Service</strong></h3>



<p>Following the first step, specify a runtime for the application. ASP.NET Core also supports operating systems where Windows Services don’t run.</p>



<p>For this, we must modify the project file. To modify the project file, double click on the Project name and add the following two lines as per the screenshot.</p>



<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="779" height="316" class="wp-image-3027 aligncenter" src="https://topreviewhostingasp.net/wp-content/uploads/2022/03/visual-studio.png" alt="" srcset="https://topreviewhostingasp.net/wp-content/uploads/2022/03/visual-studio.png 779w, https://topreviewhostingasp.net/wp-content/uploads/2022/03/visual-studio-300x122.png 300w, https://topreviewhostingasp.net/wp-content/uploads/2022/03/visual-studio-768x312.png 768w, https://topreviewhostingasp.net/wp-content/uploads/2022/03/visual-studio-50x20.png 50w" sizes="(max-width: 779px) 100vw, 779px" /></figure>
</div>



<p>Add a reference using NuGet package <strong>Microsoft.ASPNetCore.Hosting.WindowsServices</strong> and <strong>Newtonsoft.json</strong>.</p>



<p>This Package has everything needed to run an ASP.Net Core application as a Window service.</p>



<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="709" height="249" class="wp-image-3028 aligncenter" src="https://topreviewhostingasp.net/wp-content/uploads/2022/03/visual-studio-2.png" alt="" srcset="https://topreviewhostingasp.net/wp-content/uploads/2022/03/visual-studio-2.png 709w, https://topreviewhostingasp.net/wp-content/uploads/2022/03/visual-studio-2-300x105.png 300w, https://topreviewhostingasp.net/wp-content/uploads/2022/03/visual-studio-2-50x18.png 50w" sizes="(max-width: 709px) 100vw, 709px" /></figure>
</div>



<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="718" height="243" class="wp-image-3029 aligncenter" src="https://topreviewhostingasp.net/wp-content/uploads/2022/03/visual-studio-3.png" alt="" srcset="https://topreviewhostingasp.net/wp-content/uploads/2022/03/visual-studio-3.png 718w, https://topreviewhostingasp.net/wp-content/uploads/2022/03/visual-studio-3-300x102.png 300w, https://topreviewhostingasp.net/wp-content/uploads/2022/03/visual-studio-3-50x17.png 50w" sizes="(max-width: 718px) 100vw, 718px" /></figure>
</div>



<p>Now, run the application as Windows Service and configure it in the Program.cs file. In case you want to run an application as IIS Express, then there is no need to change any configuration setting, and we can directly run an application as IIS Express.</p>



<p>We can specify a different port in the <strong>appsettings.json</strong> and <strong>appsettings.Devlopment.json</strong> file to run an application on this port directly using the Windows service.</p>



<p>Specify Port no 5009.</p>



<p><strong><u>appsettings.json File:</u></strong></p>



<pre class="wp-block-code"><code>{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
	}
  },
"AllowedHosts": "*",
"ServicePort" :  5009
}
 appsettings.Devlopment.json file:
{
"DetailedErrors": true,
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
	}
  },
"ServicePort": 5009</code></pre>



<p>Moving on, to specify our <strong>appsettings.json</strong> file as Configuration path in <strong>Program.cs</strong> file to let the application read that path and run on that port. See the screenshots below.</p>



<p><strong>Program.csFile:</strong></p>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="944" height="590" class="wp-image-3030 aligncenter" src="https://topreviewhostingasp.net/wp-content/uploads/2022/03/visual-studio-4.png" alt="" srcset="https://topreviewhostingasp.net/wp-content/uploads/2022/03/visual-studio-4.png 944w, https://topreviewhostingasp.net/wp-content/uploads/2022/03/visual-studio-4-300x188.png 300w, https://topreviewhostingasp.net/wp-content/uploads/2022/03/visual-studio-4-768x480.png 768w, https://topreviewhostingasp.net/wp-content/uploads/2022/03/visual-studio-4-50x31.png 50w" sizes="(max-width: 944px) 100vw, 944px" /></figure>



<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="944" height="484" class="wp-image-3031 aligncenter" src="https://topreviewhostingasp.net/wp-content/uploads/2022/03/visual-studio-5.png" alt="" srcset="https://topreviewhostingasp.net/wp-content/uploads/2022/03/visual-studio-5.png 944w, https://topreviewhostingasp.net/wp-content/uploads/2022/03/visual-studio-5-300x154.png 300w, https://topreviewhostingasp.net/wp-content/uploads/2022/03/visual-studio-5-768x394.png 768w, https://topreviewhostingasp.net/wp-content/uploads/2022/03/visual-studio-5-50x26.png 50w" sizes="(max-width: 944px) 100vw, 944px" /></figure>
</div>



<h3 class="wp-block-heading"><strong>3.</strong> <strong>Build the application and Publish the code</strong></h3>



<p>With the above-given configuration completed in the <strong>Program.cs</strong> file start building the application, followed by publishing the code in the folder.</p>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="944" height="489" class="wp-image-3032 aligncenter" src="https://topreviewhostingasp.net/wp-content/uploads/2022/03/visual-studio-6.png" alt="" srcset="https://topreviewhostingasp.net/wp-content/uploads/2022/03/visual-studio-6.png 944w, https://topreviewhostingasp.net/wp-content/uploads/2022/03/visual-studio-6-300x155.png 300w, https://topreviewhostingasp.net/wp-content/uploads/2022/03/visual-studio-6-768x398.png 768w, https://topreviewhostingasp.net/wp-content/uploads/2022/03/visual-studio-6-50x26.png 50w" sizes="(max-width: 944px) 100vw, 944px" /></figure>



<h3 class="wp-block-heading"><strong>4. Making the application Run as WindowsService</strong></h3>



<p>To make the application run as a Windows service follow these steps;</p>



<ul>
<li>Open the Command line with administrative Permission.</li>
<li>Register the application as a Windows service using this command (<strong>space after “binPath=” is mandatory</strong>)</li>
</ul>



<p><strong>Create windows service using the following command</strong>:</p>



<p><strong>sc create AspNetCoreWindowsServicebinPath = “path to my publish folder application exe –service”</strong></p>



<p>In the example above, we have taken <strong>AspNetCoreWindowsService</strong> as the name; you can use any name you want to keep. Also, <strong>–service</strong> is an argument name that we pass in <strong>Program.cs</strong> file.</p>



<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="862" height="466" class="wp-image-3033 aligncenter" src="https://topreviewhostingasp.net/wp-content/uploads/2022/03/cmd.png" alt="" srcset="https://topreviewhostingasp.net/wp-content/uploads/2022/03/cmd.png 862w, https://topreviewhostingasp.net/wp-content/uploads/2022/03/cmd-300x162.png 300w, https://topreviewhostingasp.net/wp-content/uploads/2022/03/cmd-768x415.png 768w, https://topreviewhostingasp.net/wp-content/uploads/2022/03/cmd-50x27.png 50w" sizes="(max-width: 862px) 100vw, 862px" /></figure>
</div>



<p>Nest, open the <strong>services.msc</strong> and see your hosted Windows service with the name <strong>AspNetCoreWindowsService</strong> to start the service.</p>



<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="879" height="490" class="wp-image-3034 aligncenter" src="https://topreviewhostingasp.net/wp-content/uploads/2022/03/service.png" alt="" srcset="https://topreviewhostingasp.net/wp-content/uploads/2022/03/service.png 879w, https://topreviewhostingasp.net/wp-content/uploads/2022/03/service-300x167.png 300w, https://topreviewhostingasp.net/wp-content/uploads/2022/03/service-768x428.png 768w, https://topreviewhostingasp.net/wp-content/uploads/2022/03/service-50x28.png 50w" sizes="(max-width: 879px) 100vw, 879px" /></figure>
</div>



<p>When the service starts, open the browser and navigate to <a href="http://localhost:50009/"><strong>http://localhost:50009</strong></a> to see the web application is running. If you would remember, we had set port 5009 in the earlier steps of ASP.NET core web application development. Specifically, look for the part where we had specified it in the <strong>appsetting.json</strong> file as mentioned above.</p>



<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="840" height="494" class="wp-image-3035 aligncenter" src="https://topreviewhostingasp.net/wp-content/uploads/2022/03/localhost.png" alt="" srcset="https://topreviewhostingasp.net/wp-content/uploads/2022/03/localhost.png 840w, https://topreviewhostingasp.net/wp-content/uploads/2022/03/localhost-300x176.png 300w, https://topreviewhostingasp.net/wp-content/uploads/2022/03/localhost-768x452.png 768w, https://topreviewhostingasp.net/wp-content/uploads/2022/03/localhost-50x29.png 50w" sizes="(max-width: 840px) 100vw, 840px" /></figure>
</div>



<p>Delete windows service using the following command:</p>



<p>Stop the existing running instance before releasing the new version of the service. Once done, write the following command.</p>



<p><strong>scdeleteAspNetCoreWindowsService</strong></p>



<p>Again, <strong>AspNetCoreWindowsService i</strong>s the windows service name that we have set to give you an example.</p>



<h4 class="wp-block-heading"><strong>Conclusion</strong></h4>



<p>This blog takes you through the steps to set up a hosting environment for <strong>ASP.NET Core 3.1 web application development in Windows Service</strong>. Although the process is simple enough to understand, we at <strong>DEV IT</strong> have understood the nuances of the same along with knowing everything about <strong>agile development practices</strong>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://topreviewhostingasp.net/how-to-host-asp-net-core-in-window-service/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>How to Run .NET Core Generic as Windows Service</title>
		<link>https://topreviewhostingasp.net/how-to-run-net-core-generic-as-windows-service/</link>
					<comments>https://topreviewhostingasp.net/how-to-run-net-core-generic-as-windows-service/#respond</comments>
		
		<dc:creator><![CDATA[Jacques Hunt]]></dc:creator>
		<pubDate>Tue, 29 Oct 2019 04:41:34 +0000</pubDate>
				<category><![CDATA[Hosting Tips]]></category>
		<category><![CDATA[asp net core windows service]]></category>
		<category><![CDATA[asp.net core]]></category>
		<category><![CDATA[asp.net core tips]]></category>
		<category><![CDATA[asp.net core tutorial]]></category>
		<guid isPermaLink="false">https://topreviewhostingasp.net/?p=2769</guid>

					<description><![CDATA[Net Core 2.2 provides Web Host for hosting web applications and Generic Host that is suitable for hosting a wider array of host apps. In the .Net Core 3 Generic Host will replace Web Host.  Generic Host will be suitable for hosting any kind of app including web applications. I looked at many examples but found that none showed [&#8230;]]]></description>
										<content:encoded><![CDATA[
<p>Net Core 2.2 provides <a href="https://topreviewhostingasp.net/best-asp-net-core-3-hosting/">Web Host</a> for hosting web applications and <a href="https://docs.microsoft.com/en-au/aspnet/core/fundamentals/host/generic-host?view=aspnetcore-2.2" target="_blank" rel="noreferrer noopener">Generic Host</a> that is suitable for hosting a wider array of host apps. In the .Net Core 3 Generic Host will replace Web Host.  Generic Host will be suitable for hosting any kind of app including web applications.</p>



<p>I looked at many examples but found that none showed the complete implementation of the Generic Host that is implemented to run as a console, Linux daemon, and Windows Service all in one application.</p>



<p>Here we will be looking at extending sample_service_hosting app to run it as a console app, windows service, or Linux daemon as well as making it self installable windows service.</p>



<p>.Net Core provides <em>IHostBuilder</em> interface to configure and create host builder. In case of a console app, host builder will run <em>await RunConsoleAsync()</em> function. To host and run our Generic Host as Windows Service we will need to use <em>IApplicationLifetime</em> to register Start and Stop events.</p>



<p>For hosting our Generic Host in Linux daemon we are going to inject <em>IApplicationLifetime</em> into main service and register and handle Start and Stop events.</p>



<p>There are several ways we could go to extend it to run as Windows Service, console app and Linux daemon. One way is to have a separate .Net Core project that will host our sample generic host service for each case or allow the program to accept command line variables that specify how to run the program. We will implement the command line arguments.</p>



<p><strong>Command-line options:</strong></p>



<ul>
<li>-i    Install as Windows Service</li>
<li>-u  Uninstall Windows Service</li>
<li>-console Run as a console app</li>
<li>-daemon Run as Linux daemon service</li>
<li>-h  Show command line switch help</li>
</ul>



<h2 class="wp-block-heading">Let’s make Argument Parser</h2>



<p>In order to parse the arguments passed to the application, we will implement an argument parser class, which will return <em>HostAction</em> enum that specifies how the application is going to start. The application will accept only one argument on its input. If more than one argument supplied or it is an invalid argument, it will show usage message. If no arguments supplied it will try to run as Windows Service.</p>



<h3 class="wp-block-heading">HostAction enum</h3>



<pre class="wp-block-code"><code>namespace VSC
{
    public enum HostAction
    {
        ShowUsage,
        InstallWinService,
        UninstallWinService,
        RunWinService,
        WinServiceStop,
        RunConsole,
        RunLinuxDaemon
    }
}</code></pre>



<h3 class="wp-block-heading">Argument Parser class – ArgsParser</h3>



<pre class="wp-block-code"><code>namespace VSC
{
    internal class ArgsParser
    {
        private string[] _args = null;
        public ArgsParser(string[] args)
        {
            _args = args;
        }

        public HostAction GetHostAction()
        {
            HostAction action = HostAction.ShowUsage;

            if(_args == null || _args.Length == 0)
            {
                action = HostAction.RunWinService;
            }
            else if(_args.Length &gt; 1)
            {
                action = HostAction.ShowUsage;
            }
            else
            {
                string argument = _args[0];

                if(argument == "-i")    // install
                {
                    action = HostAction.InstallWinService;
                }
                else if(argument == "-u")   // uninstall
                {
                    action = HostAction.UninstallWinService;
                }
                else if(argument == "-console")
                {
                    action = HostAction.RunConsole;
                }
                else if (argument == "-daemon")
                {
                    action = HostAction.RunLinuxDaemon;
                }
            }

            return action;
        }
    }
}</code></pre>



<h2 class="wp-block-heading">Let’s make HostedService class</h2>



<p>At the moment sample_service_hosting app creates host builder by calling <em>CreateHostBuilder()</em> from the Main function. We need to introduce a class that will perform an action depending on what HostAction returned by ArgsParser. We will call it <em>HostedService</em> class. It will have an async Run function that will start different action.</p>



<p>For now let’s implement run as a console, run as Linux daemon and show usage actions. Function <em>CreateHostBuilder()</em> will be moved from Program.cs to <em>HostedService</em> class.</p>



<h3 class="wp-block-heading">HostedService class</h3>



<pre class="wp-block-code"><code>using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using NLog.Extensions.Hosting;

namespace VSC
{
    internal class HostedService
    {
        private static NLog.Logger _logger = NLog.LogManager.GetCurrentClassLogger();

        private ArgsParser _argsParser = null;

        public HostedService(ArgsParser argsParser)
        {
            _argsParser = argsParser;
        }

        public async Task Run(string[] args)
        {
            if (_argsParser != null)
            {
                var builder = this.CreateHostBuilder(args);
                
                if(builder == null) return;

                switch (_argsParser.GetHostAction())
                {
                    case HostAction.InstallWinService:
                    {
                        
                    }
                    break;
                    case HostAction.UninstallWinService:
                    {
                        
                    }
                    break;
                    case HostAction.RunWinService:
                    {
                        
                    }
                    break;
                    case HostAction.RunConsole:
                    {
                        try
                        {
                            await builder.RunConsoleAsync();
                        }
                        catch(Exception ex)
                        {
                            _logger.Error("Could not run as console app. " + ex.Message);
                            ShowUsage();
                        }
                    }
                    break;
                    case HostAction.RunLinuxDaemon:
                    {
                        try
                        {
                            await builder.Build().RunAsync();
                        }
                        catch(Exception ex)
                        {
                            _logger.Error("Could not start as Linux daemon service. " + ex.Message);
                            ShowUsage();
                        }
                    }
                    break;
                    default:
                    {
                        ShowUsage();
                    }
                    break;
                } 
            }   
        }

        private void ShowUsage()
        {   
            Console.WriteLine("Options:\n"
                        + "  'no options'\tStart Windows Service\n"
                        + "  -i\t\tInstall as Windows Service\n"
                        + "  -u\t\tUninstall Windows Service\n"
                        + "  -console\tRun as console app\n"
                        + "  -daemon\t Run as Linux daemon service\n"
                        + "  -h\t\tShow command line switch help\n");
        }
        private IHostBuilder CreateHostBuilder(string[] args)
        {
            try
            {
                var builder = new HostBuilder()
                    .UseNLog()
                    .ConfigureAppConfiguration((hostingContext, config) =&gt;
                    {
                        config.SetBasePath(Directory.GetCurrentDirectory());
                        config.AddJsonFile("appsettings.json", optional: true);
                        config.AddJsonFile(
                            $"appsettings.{hostingContext.HostingEnvironment.EnvironmentName}.json", 
                            optional: true);
                        config.AddCommandLine(args);
                    })
                    .ConfigureServices((hostContext, services) =&gt;
                    {
                        services.AddHostedService&lt;Services.SampleService&gt;();
                        services.Configure&lt;HostOptions&gt;(option =&gt;
                        {
                            option.ShutdownTimeout = System.TimeSpan.FromSeconds(20);
                        });
                    })
                    .ConfigureLogging((hostingContext, logging) =&gt; 
                    {
                        logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
                        logging.AddConsole();
                    });

                return builder;
            }
            catch { }

            return null;
        }
    }
}</code></pre>



<p>In Program.cs we change code as follows.</p>



<h3 class="wp-block-heading">Program.cs</h3>



<pre class="wp-block-code"><code>using System.Threading.Tasks;

namespace VSC
{
    class Program
    {   
        static async Task Main(string[] args)
        {
            ArgsParser argsParser = new ArgsParser(args);

            HostedService service = new HostedService(argsParser);
            await service.Run(args);
        }
    }
}</code></pre>



<h2 class="wp-block-heading">Let’s Make it self installable Windows Service</h2>



<p>Now we got to the point of making our sample app to run as Windows Service. As Software Developer we always try to make the life of our users easier. If the app will be able to self install/uninstall as windows service our users will be much happier than trying to do that themselves.</p>



<p>We will start in the external process <em>sc.exe</em> service controller tool with parameters to install/uninstall/stop service. Example:<ins></ins></p>



<ul>
<li>sc.exe create “service_name” displayname= “service_name” binpath= “path to exe file”</li>
<li>sc.exe delete “service_name”</li>
<li>sc.exe stop “service_name”</li>
</ul>



<p><em>WinServiceInstaller</em> class will be responsible for running an external process and notifying of the progress. We will use <em>WinService</em> class to handle Start, Stop events and use extension functions to inject our WinService class into our Generic Host Builder.</p>



<h3 class="wp-block-heading">WinService class</h3>



<pre class="wp-block-code"><code>using System;
using System.ServiceProcess;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;

namespace VSC
{
    public class WinService : ServiceBase, IHostLifetime
    {
        public static string WinServiceName = "Default Service Name";
        private readonly TaskCompletionSource&lt;object&gt; _delayStart = new TaskCompletionSource&lt;object&gt;();

        private IApplicationLifetime ApplicationLifetime { get; }

        public WinService(IApplicationLifetime applicationLifetime)
        {
            this.ServiceName = WinServiceName;

            ApplicationLifetime = applicationLifetime ?? throw new ArgumentNullException(nameof(applicationLifetime));
        }        

        public void Start()
        {
            try
            {
                Run(this); // This blocks until the service is stopped.
                _delayStart.TrySetException(new InvalidOperationException("Stopped without starting"));
            }
            catch (Exception ex)
            {
                _delayStart.TrySetException(ex);
            }

            this.OnStart(null);
        }

        public Task StopAsync(CancellationToken cancellationToken)
        {
            Stop();
            return Task.CompletedTask;
        }

        public Task WaitForStartAsync(CancellationToken cancellationToken)
        {
            cancellationToken.Register(() =&gt; _delayStart.TrySetCanceled());
            ApplicationLifetime.ApplicationStopping.Register(Stop);

            new Thread(Start).Start(); // Otherwise this would block and prevent IHost.StartAsync from finishing.
            return _delayStart.Task;
        }

        protected override void OnStart(string[] args)
        {
            _delayStart.TrySetResult(null);
            base.OnStart(args);
        }

        protected override void OnStop()
        {
            ApplicationLifetime.StopApplication();
            base.OnStop();
        }
    }
}</code></pre>



<h3 class="wp-block-heading">WinServiceInstaller class</h3>



<pre class="wp-block-code"><code>using System.Diagnostics;

namespace VSC
{
    public static class WinServiceInstaller
    {
        private static NLog.Logger _logger = NLog.LogManager.GetCurrentClassLogger();

        public static string APP_EXECUTABLE_PATH = string.Empty;
        private const string ServiceControllerEXE = "sc.exe";

        public delegate void WinServiceStatusHandler (string status);
        public static event WinServiceStatusHandler WinServiceStatus;

        public static void Uninstall(string serviceName)
        {
            Stop(serviceName); // stop service before uninstall

            RaiseWinServiceStatus("Uninstall Service");

            RunProcess(string.Format("delete \"{0}\"", serviceName));
        }

        private static void Stop(string serviceName)
        {
            RaiseWinServiceStatus("Stopping Service");

            RunProcess(string.Format("stop \"{0}\"", serviceName));            
        }

        public static void Install(string serviceName)
        {
            if(!string.IsNullOrEmpty(APP_EXECUTABLE_PATH))
            {
                RaiseWinServiceStatus("Install Service");

                string processArguments = string.Format("create \"{0}\" displayname= \"{1}\" binpath= \"{2}\"", serviceName, serviceName, APP_EXECUTABLE_PATH);
                
                RunProcess(processArguments);
            }
            else
            {
                _logger.Error("Cannot install service. Path to exe cannot be empty.");
            }
        }

        private static void RaiseWinServiceStatus(string status)
        {
            if(WinServiceStatus != null)
            {
                WinServiceStatus(status);
            }
        }

        private static void RunProcess(string arguments)
        {
            _logger.Trace("Arguments: " + arguments);

            var process = new Process();
            var processInfo = new ProcessStartInfo();
            processInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
            processInfo.FileName = ServiceControllerEXE;
            processInfo.Arguments = arguments;
            process.StartInfo = processInfo;
            process.Start();
            process.WaitForExit();
        }
    }
}</code></pre>



<h3 class="wp-block-heading">WinServiceExtensions static class</h3>



<pre class="wp-block-code"><code>using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace VSC
{
    public static class WinServiceExtensions
    {
        internal static IHostBuilder UseServiceBaseLifetime(this IHostBuilder hostBuilder)
        {
            return hostBuilder.ConfigureServices((hostContext, services) =&gt; services.AddSingleton&lt;IHostLifetime, WinService&gt;());
        }

        public static Task RunAsWindowsServiceAsync(this IHostBuilder hostBuilder, CancellationToken cancellationToken = default)
        {
            return hostBuilder.UseServiceBaseLifetime().Build().RunAsync(cancellationToken);
        }
    }
}</code></pre>



<p>We need to add to our project package reference <em>System.ServiceProcess.ServiceController</em> in order to compile <em>WinService</em> class.</p>



<pre class="wp-block-code"><code>dotnet add package System.ServiceProcess.ServiceController</code></pre>



<p>Now in <em>HostedService</em> Run function, we can implement remaining switch cases that will Install, Uninstall and Run our app as windows service.</p>



<pre class="wp-block-code"><code>internal class HostedService
{
    ...

    public async Task Run(string[] args)
    {
        if (_argsParser != null)
        {
            var builder = this.CreateHostBuilder(args);
                
            if(builder == null) return;

            WinServiceInstaller.APP_EXECUTABLE_PATH = Utility.GetExecutingAssemblyLocation().Remove(Utility.GetExecutingAssemblyLocation().Length - 4) + ".exe";
                
            switch (_argsParser.GetHostAction())
            {
                case HostAction.InstallWinService:
                {
                    WinServiceInstaller.Install(WinService.WinServiceName);
                }
                break;
                case HostAction.UninstallWinService:
                {
                    WinServiceInstaller.Uninstall(WinService.WinServiceName);
                }
                break;
                case HostAction.RunWinService:
                {
                    try
                    {
                        await builder.RunAsWindowsServiceAsync();
                    }
                    catch(Exception ex)
                    {
                        _logger.Error("Could not start as windows service. " + ex.Message);
                        ShowUsage();
                    }
                }
                break;

    ...
}</code></pre>



<p>You may have noticed that APP_EXECUTABLE_PATH is set by calling utility function <em>GetExecutingAssemblyLocation</em> in Utility class.</p>



<h3 class="wp-block-heading">Utility static class</h3>



<pre class="wp-block-code"><code>namespace VSC
{
    public static class Utility
    {
        public static string GetExecutingAssemblyLocation()
        {
            return System.Reflection.Assembly.GetExecutingAssembly().Location;
        }
    }
}</code></pre>



<h2 class="wp-block-heading">Let’s update the Main function</h2>



<p>As the final step, we will update our Program.cs and add the logger to print status of our Windows Service. At the end before closing application, we also need to Flush logger and shut it down to release resource when our app will run as Linux daemon.</p>



<h3 class="wp-block-heading">Program.cs</h3>



<pre class="wp-block-code"><code>using System;
using System.Threading.Tasks;
using NLog;
using System.Reflection;

namespace VSC
{
    class Program
    {   
        private static Logger _logger = NLog.LogManager.GetCurrentClassLogger();

        static async Task Main(string[] args)
        {
            ArgsParser argsParser = new ArgsParser(args);

            WinService.WinServiceName = "The Sample Service Host";
            WinServiceInstaller.WinServiceStatus += new WinServiceInstaller.WinServiceStatusHandler(PrintWinServiceStatus);

            _logger.Info("Version: " + Assembly.GetEntryAssembly().GetName().Version.ToString());

            HostedService service = new HostedService(argsParser);
            await service.Run(args);

            _logger.Info("Shutting down logger...");
            // Flush buffered log entries before program exit; then shutdown the logger before program exit.
            LogManager.Flush(TimeSpan.FromSeconds(15));
            LogManager.Shutdown();
        }

        private static void PrintWinServiceStatus(string status)
        {
            _logger.Info(status);
        }
    }
}</code></pre>



<h2 class="wp-block-heading">Summary</h2>



<p>Today we extended sample_service_hosting app with the ability to run as windows service and self install/uninstall itself to make it easier to deploy as windows service. We could go down the path of implementing separate projects: one for a console app, one for Linux daemon, one for windows service and one common project with our SampleService Host. We managed to do it all in one project with the use of ArgsParser class and extension functions to inject our Host into <em>WinService</em>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://topreviewhostingasp.net/how-to-run-net-core-generic-as-windows-service/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
