When you create a regular .NET 5 or 6 API project, you get some basic classes such as Program.cs and Startup.cs. I want to replicate that in a class project, because I want to be able to configure my services for dependency injection, but I don't want any controllers or HTTP in my project. As an example, let's assume I want to create a .NET 6 project using minimal API/hosting, and I want to check for file changes in a directory:
Program.cs
static async Task Main(string[] args)
{
await CreateHostBuilder(args).Build().RunAsync();
}
static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureServices((_, services) => ConfigureServices(services));
static void ConfigureServices(IServiceCollection services)
{
services.AddTranscient<IFileListener, FileListener>();
}
This is probably a good starting point, which is quite similar to Startup.cs in an API project.
Inside my FileListener class, I want to call a method, that listens for file changes in a folder. Let's call it StartListening(). Where would I call that method? At some point I guess I need to do something like:
var fileListenerService = ((IServiceCollection)services).BuildServiceProvider().GetService<IListener>();
await fileListenerService.StartListening();
But where? Inside the Main method? Inside ConfigureServices? Somewhere else?
Maybe I'm looking at this the wrong way, but essentially I just need to call a method and make it run that method until the application is closed.
CodePudding user response:
Microsoft's hosting has a concept of hosted services to handle background tasks, so you can turn your FileListener into hosted service and register it in DI with AddHostedService and the hosting will start it automatically with DI and cancelation signaling support.
Note that consuming scoped services from the hosted service requires a little bit extra work.
