Reputation: 2523
We have an existing windows service that hosts some of our WCF services. These are some of our integration API-s.
What we would like to do is start an Asp.Net Core application in this windows service. This Asp.Net Core application is in separate project and we would like to keep it there. This project would be compiled as ClassLibrary.
This wouldn't be done like in common articles you find on google when you type in "Asp.Net Core as Windows service"...
I found this question but the answer is not suitable. We would like to avoid registering this as a separate service because of the extra work needed in the installation process.
I also thought that if I build the IWebHost and call run on a separate thread that it would work. Indeed the web server starts but all the requests I make to it are invalid as in nothing happens at all.
Has anybody had any experience with this kind of problem?
Upvotes: 4
Views: 1639
Reputation: 757
Class Library project file (targets netstandard2.0)
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Hosting" Version="2.2.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc" Version="2.2.0" />
</ItemGroup>
</Project>
Service Program.cs (targets net472)
class Program
{
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup(typeof(Startup).Assembly.FullName);
public static void Main(string[] args)
{
Task.Run(() => CreateWebHostBuilder(args).Build().Run());
var rc = HostFactory.Run(x => //1
{
x.Service<TownCrier>(s => //2
{
s.ConstructUsing(name=> new TownCrier()); //3
s.WhenStarted(tc => tc.Start()); //4
s.WhenStopped(tc => tc.Stop()); //5
});
x.RunAsLocalSystem(); //6
x.SetDescription("Sample Topshelf Host"); //7
x.SetDisplayName("Stuff"); //8
x.SetServiceName("Stuff"); //9
}); //10
var exitCode = (int) Convert.ChangeType(rc, rc.GetTypeCode()); //11
Environment.ExitCode = exitCode;
}
}
public class TownCrier
{
readonly Timer _timer;
public TownCrier()
{
_timer = new Timer(1000) {AutoReset = true};
_timer.Elapsed += (sender, eventArgs) => Console.WriteLine("It is {0} and all is well", DateTime.Now);
}
public void Start() { _timer.Start(); }
public void Stop() { _timer.Stop(); }
}
The Service required adding a couple of nuget packages:
Upvotes: 1