1

Do I need to dispose the dbconext in the GetSubmissionDetailsAsync method?

public void ConfigureServices(IServiceCollection services)
{
   services.AddScoped(provider=>provider.GetService<IMLDbContextFactory().CreateElmsDbContext());
}

  public ElmsContext CreateElmsDbContext()
  {
            var connectionString = _configuration.GetConnectionString("elmsdatabase");
                var optionsBuilder = new DbContextOptionsBuilder<ElmsContext>()
                .UseSqlServer(connectionString);
            return new ElmsContext(optionsBuilder.Options);
  }

public class DataAccessObject : IDataAccessObject
    {
        private readonly ILoggerAdapter<DataAccessObject> _logger;
        private readonly ElmsContext _elmsContext;
        private readonly ElmsPolicyContext _elmsPolicyContext;

        public DataAccessObject(ElmsContext elmsContext, ElmsPolicyContext elmsPolicyContext, ILoggerAdapter<DataAccessObject> logger)
        {
            _logger = logger;
            _elmsContext = elmsContext;
            _elmsPolicyContext = elmsPolicyContext;
        }
     public async Task<CertifiedBusinessSubmissionDto> GetSubmissionDetailsAsync(int? submissionId)
     {     
                var subId = new SqlParameter("submission_id", submissionId);
                var submission = await _elmsContext.CertifiedBusinessSubmissionDTO
                    .FromSqlRaw("EXECUTE dbo.get_info @submission_id", subId)
                    .ToListAsync();
              
                return submission != null && submission.Count > 0 ? submission.FirstOrDefault() : null;
     }
}
retide
  • 1,170
  • 1
  • 13
  • 31

1 Answers1

0

Although the DbContext implements IDisposable, you shouldn't manually dispose it, nor should you wrap it in a using statement. DbContext manages its own lifetime; when your data access request is completed, DbContext will automatically close the database connection for you. You can check this post and the answer there is given by Diego Vega (the Senior SDE Lead on EF) https://blog.jongallant.com/2012/10/do-i-have-to-call-dispose-on-dbcontext/

There are special cases in which dispose should be applied, but according to the code you provided above, there is no need to explicitly apply dispose.

Darkk L
  • 889
  • 1
  • 4
  • 14
  • *DbContext manages its own lifetime*. That's not true. Implementing `IDisposable` doesn't mean that the object disposes itself. It means it can *be* disposed, which is passive. But yes, by default, the context closes connections after each db interaction so usually it's not even worth worrying whether it's disposed or not. (It takes deliberate steps to make a context not close the connection). – Gert Arnold Mar 30 '22 at 10:08
  • I did not say that dbContext dispose itself, but manages itself so that it is not necessary to call dispose . Оf course except in special cases. – Darkk L Mar 30 '22 at 10:25
  • I edited my post , because I had error that causes confusion in the sense of what I have written. – Darkk L Mar 30 '22 at 10:46
  • But it doesn't manage its own *lifetime*. As the post says, it manages its own *connection*. – Gert Arnold Mar 30 '22 at 12:51
  • All you are saying it is not need to manually call dispose method. And dbcontext will handle close connection itself. So i should not worry about memory leak from my code ? – retide Mar 30 '22 at 13:38
  • The default automatic open/close behavior is relatively easy to override: you can assume control of when the connection is opened and closed by manually opening the connection. Once you start doing this in some part of your code, then forgetting to dispose the context becomes harmful, because you might be leaking open connections. In that case you can dispose the context if you are not sure is the connection opened automatically or manually. – Darkk L Mar 30 '22 at 14:35
  • For the lifetime of the dbContext you can check this post here https://stackoverflow.com/questions/37507691/entity-framework-core-service-default-lifetime – Darkk L Mar 30 '22 at 14:47
  • I have tested my codes I can see I am hold the dbcontext to long. The phonetical risk is hold dbcontext too long. exmaple: call sp1-> do somework -> call sp 2-> do somework -> close connection. It is working on if the traffic is low. when traffic is high I feel it will run out connections. It should be sp1->dispose dbcontext->do somework -> call sp2 -> dispose context -> do some work – retide Apr 14 '22 at 15:08