I have created API using asp.net-core-web-api template. So I have deployed to production and when API started to processing a lot of request I paid attention to the memory.
When I was testing the API with DotMemory I noticed this:
In each jump, I’ve sending 100 request from script:
int i = 100;
for (var i1 = 0; i1 < i; i1++)
{
var httpClient = new HttpClient();
await httpClient.GetAsync("https://localhost:5001/api/tags");
}
I waited more than 5 minutes, but memory usage did not decrease.
This is the code that is called by the controller:
using Microsoft.EntityFrameworkCore;
using MRA.Jobs.Application.Contracts.Tags;
namespace MRA.Jobs.Application.Features.Tags;
public class GetTagsQueryHandler(IApplicationDbContext dbContext) : IRequestHandler<GetTagsQuery,List<string>>
{
public async Task<List<string>> Handle(GetTagsQuery request, CancellationToken cancellationToken)
{
return (await dbContext.Tags.Select(t => t.Name).Distinct().ToListAsync(cancellationToken));
}
}
This is TagsController code:
using Microsoft.AspNetCore.Mvc;
using MRA.Jobs.Application.Contracts.Tags;
namespace MRA.Jobs.Web.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class TagsController : ApiControllerBase
{
[HttpGet]
public async Task<IActionResult> Get()
{
return Ok(await Mediator.Send(new GetTagsQuery()));
}
}
}
This is my dbContext registration to DI:
services.AddDbContext<ApplicationDbContext>(options =>
{
string dbConnectionString = configuration.GetConnectionString("DefaultConnection");
if (configuration["UseInMemoryDatabase"] == "true")
options.UseInMemoryDatabase("testDb");
else
options.UseSqlServer(dbConnectionString);
});
services.AddScoped<IApplicationDbContext, ApplicationDbContext>();
Dotmemory after 13 minutes from requests:
So I don’t want to restart my server every hour :), what should I do? How can I fix that issue?