I'm creating a background service in .NET 8, but I get the below error
Error CS0118 'BackgroundService' is a namespace but is used like a type
This was working in .NET 6 version.
I have uninstalled and reinstalled Microsoft.Extensions.Hosting but does not seem to work.
Creating new project and facing this issue:
using Microsoft.Extensions.Hosting;
namespace BackgroundService
{
public class Worker : BackgroundService
{
private readonly ILogger<Worker> _logger;
public Worker(ILogger<Worker> logger)
{
_logger = logger;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
if (_logger.IsEnabled(LogLevel.Information))
{
_logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
}
await Task.Delay(1000, stoppingToken);
}
}
}
}
Change the namespace BackgroundService
to something else otherwise it shadows the type name:
namespace MyApp.BackgroundServices
{
public class Worker : BackgroundService
{
// ...
}
}
Alternatively you can specify the fully qualified type name (though I would argue that the first option should be preferred):
public class Worker : Microsoft.Extensions.Hosting.BackgroundService
{
// ...
}