Service Fabric SDK 2.1.150 comes with an ASP.NET Core project template so you can easily include a web app or web service in your Service Fabric application. To get started follow this official article: Build a web service front end for your application, but for more advanced scenarios such as hosting your .Net Core web application outside Service Fabric (for those times you just don’t want to deploy), forcing Kestrel to listen to all machine assigned IP addresses, we’ll customise and extend the starter template generated code. Moreover, with .Net Core RC2 and RTM the ubiquitous dotnet.exe becomes our preferred tool of choice so let’s facilitate running your Service Fabric Web app for development and debugging with the same simple command dotnet.exe run.
As always and given I am still targeting .Net Core RC2, we’ll start with the required project.json dependencies which should look something like the below. For command line argument heavily lifting include the “CommandLineParser”: “2.0.275-beta” package.
In your Program.cs which contains the generated starter template code add the following usings:
1 2 3 4 5 6 7 8 9
using CommandLine; using Microsoft.AspNetCore.Hosting; using Microsoft.ServiceFabric.Services.Communication.Runtime; using Microsoft.ServiceFabric.Services.Runtime; using System; using System.Collections.Generic; using System.Fabric; using System.Threading; using System.Threading.Tasks;
Since we want to host our .Net Core web application both within Service Fabric and outside for quick turnaround during development and debugging without the hassle of always deploying, we modify Main to support both scenarios:
AcmeConstants.ServiceFabricHost - value of command line argument: service-fabric-host AcmeConstants.SelfHost - value of command line argument: self-host
We then need to create an Options class to be used by the CommandLineParser:
[Option(Default = "http", HelpText = "The target protocol - Options [http] or [https]")] publicstring Protocol { get; set; }
[Option(Default = "localhost", HelpText = "The target IP Address or Uri - Example [localhost] or [127.0.0.1]")] publicstring IpAddressOrFQDN { get; set; }
[Option(Default = "5000", HelpText = "The target port - Example [80] or [5000]")] publicstring Port { get; set; } }
We replace the generated OpenAsync code with the following version:
Note, I prefer to use the following which instructs Kestrel to listen to all IP addresses assigned to the machine on the port specified:
.UseUrls($"{protocol}://+:{port}")
All that is now left to do is within your .Net Core Web Application PackageRoot, edit the ServiceManifest.xml CodePackage so that we tell Web.exe to “host” within Service Fabric in this scenario:
Your .Net Core Web application will now run both within Service Fabric and in debug mode. To run from the command line, from within your Web application folder issue: