Service Worker with .NET Core 3

Net Core 3 is about to be released, until now it was more complex to create batches with this framework.

Create project

With .NET Core 3 a new project type is arriving: Service Worker. It is located for the moment under ASP.NET Core application template.Project Service Worker

These will create a ServiceWorker with NET Core, but in order to be able to run it like a Windows Service the following Nuget packet needs to be installed:

Once the package is installed the program class has to be modified like this:


public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}

public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.UseWindowsService()
.ConfigureServices(services =>
{
services.AddHostedServices();
});
}

 
It’s the « UseWindowsService() which will change the lifetime of the application.

However this lifetime will be only changed if the application is registered as a Windows Service, in other hands it will not be changed the lifetime, and will remains linked to console application lifetime which is killed by CTRL+C.
The first check made by « UseWindowsService » is if(WindowsServiceLifetimeHostBuilderExtensions.IsWindowsService())
If the application is registered as a Services it will also configure logging.

Publishing as a Service Windows

First, you need to publish your code with the CLI command
dotnet publish -o pathToRepertory
Then you have to register the service with the « sc » command:
sc create serviceworker binPath=pathToArtifact

Using Autofac instead of .NET Core IoC

If you wish to use Autofac instead of the native container you have to add the Autofac Nuget package and Autofac.Extensions.DependencyInjection.
Then the method CreateHostBuilder of the program class has to be modified like follow:

public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.UseWindowsService()
.UseServiceProviderFactory(new AutofacServiceProviderFactory())
.ConfigureServices(services =>
{
services.AddHostedService();
})
.ConfigureContainer(builder =>
{

});

Conlusion

You will now be able to generate Windows Services with .NET Core 3 and use Autofac as a container.

Répondre

Entrez vos coordonnées ci-dessous ou cliquez sur une icône pour vous connecter:

Logo WordPress.com

Vous commentez à l'aide de votre compte WordPress.com. Déconnexion /  Changer )

Photo Google

Vous commentez à l'aide de votre compte Google. Déconnexion /  Changer )

Image Twitter

Vous commentez à l'aide de votre compte Twitter. Déconnexion /  Changer )

Photo Facebook

Vous commentez à l'aide de votre compte Facebook. Déconnexion /  Changer )

Connexion à %s