I am using EF Core in my ASP.NET MVC Core (v1) application. And I notice while hosting my app on production for testing, the IIS Server normally recycles quite frequently due to reaching its memory limit.
I wanted to verify if the way I am using my dbContext
in my application is valid and is not creating any memory leaks in the background. I have read some similar posts on SO where people recommend to dispose the context object after using it.
But I used it via dependency injection as follows.
Startup.cs class snippet:
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<Context>();
}
Context.cs class snippet:
public class Context : IdentityDbContext<ApplicationUser>
{
private IConfigurationRoot _config;
private IHttpContextAccessor _HttpContextAccessor;
public Context(IConfigurationRoot config, DbContextOptions options, IHttpContextAccessor HttpContextAccessor)
: base(options)
{
_config = config;
_HttpContextAccessor = HttpContextAccessor;
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
base.OnConfiguring(optionsBuilder);
optionsBuilder.UseSqlServer(_config["ConnectionStrings:ContextConnection"]);
}
}
Does the services.AddDbContext<Context>
inject a shared instance of the context, which results in a buildup of all entities queried over time and therefore is eating up memory?
EDIT: I also have a couple of the following singleton instances as follows:
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddSingleton<ILoggerService, LoggerService>();
services.AddSingleton<IEmailSender, EmailSender>();
Thanks!