Home > Back-end >  Cannot access APIs when add IHostedService service in ASP.NET Core
Cannot access APIs when add IHostedService service in ASP.NET Core

Time:05-20

I use .NET 6 and when I add an IHostedService service in ASP.NET Core, I cannot access the APIs. If I remove the IHostedService, I can access the APIs.

Add IHostedService:

//builder.Services.AddHostedService<WSService>();
builder.WebHost.ConfigureServices(services => services.AddHostedService<WSService>());
public class WSService : IHostedService
{
    public async Task StartAsync(CancellationToken cancellationToken)
    {
        while (true)
        {
            System.Console.WriteLine("back ground task");
            await Task.Delay(5 * 1000);
        }
    }
    public async Task StopAsync(CancellationToken cancellationToken)
    {
        await Task.CompletedTask;
    }
}

If add IHostedService, cannot access http://localhost:5000/Query

namespace Api.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class QueryController : ControllerBase
    {
        private readonly IQueryData _queryData;

        public QueryController(IQueryData queryData)
        {
            _queryData = queryData;
        }

        [HttpGet]
        public async Task<IActionResult> Query([FromQuery] QueryDataRequest request, CancellationToken cancellationToken)
        {
            var data = await _queryData.PagingQueryAsync(request, cancellationToken);
            return new JsonResult(data);
        }

    }
}

Add IHostedService will not print these logs, it seems the WebHost is not running enter image description here

So, how to resolve this problem, thanks!

CodePudding user response:

You are causing an infinite loop on your StartAsync method, and as noted by the documentation here:

StartAsync should be limited to short running tasks because hosted services are run sequentially, and no further services are started until StartAsync runs to completion.

  • Related