1

Please don't mark this as duplicate because this doesn't seem duplicate as other stack overflow questions.

I have this code which looks perfect and also works as expected but sometimes it throws exception. Here is the code

try
{
    using (var db = new ClubrContext())
    {
        var notificationService = new PushNotificationService(_logger);
        var sendMailService = new SendMailService(_logger);
        var smsService = new SMSService(_logger, sendMailService);
        var reminderService = new GuestQuestionReminderService(notificationService, _logger, db, smsService);
        await reminderService.SendReminders();
    }
}
catch (Exception ex)
{

}

And the code for SendReminder function looks as below -

public class GuestQuestionReminderService : BaseReminderService
{
    public GuestQuestionReminderService(IPushNotificationService notificationService, ILoggerService loggerService, ClubrContext dbContext, ISMSService smsService) :
        base(notificationService, loggerService, dbContext, smsService)
    {            
    }
    public async Task SendReminders()
    {
        try
        {
            var groups = DbContext.Groups
                .Include("Messages")
                .Include("Admin")
                .Include("Admin.Profile")
                .Include("Promoter")
                .Include("Promoter.Profile")
                .Where(x => !x.Deleted && x.PartyDate >= DateTime.Today && x.Offers.Any() && x.Offers.Any(offer => offer.IsAccepted && !offer.Deleted))
                .ToList();

            foreach (var group in groups)
            {
                var offer = group.Offers.FirstOrDefault(x => x.IsAccepted && !x.Deleted);
                var lastPromoterMessageDate = offer.Messages.OrderByDescending(x => x.MessageDate).FirstOrDefault(x => x.FromUserId == group.PromoterId)?.MessageDate;
               lastPromoterMessageDate = lastPromoterMessageDate ?? DateTime.MinValue;
                var recentAdminMessages = offer.Messages.Where(x => x.FromUserId == group.AdminId && x.MessageDate > lastPromoterMessageDate).ToList();            
            }
        }
        catch (Exception ex)
        {
            LoggerService.Error(ex, ex.StackTrace);
        }
    }
}

At first glance, everything seems correct. All calls to database are with-in using statement yet exception is thrown!

I read in one forum that this can be because of incorrect connection string but I'm not sure if that's ready true. Still providing connection string here -

Data Source=[Data Source];Initial Catalog=[Database];User ID=[User Id];Password=[Password];MultipleActiveResultSets=true;

Here is exception stack trace -

System.InvalidOperationException: The operation cannot be completed because the DbContext has been disposed.
System.InvalidOperationException: The operation cannot be completed because the DbContext has been disposed.
at System.Data.Entity.Internal.LazyInternalContext.InitializeContext()at System.Data.Entity.Internal.LazyInternalContext.GetObjectContextWithoutDatabaseInitialization()
at System.Data.Entity.Internal.InternalContext.UpdateEntitySetMappingsForType(Type entityType)
at System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType)
at System.Data.Entity.Internal.Linq.InternalSet`1.Initialize()
at System.Data.Entity.Internal.Linq.InternalSet`1.Include(String path)
at System.Data.Entity.Infrastructure.DbQuery`1.Include(String path)     
at System.Data.Entity.Internal.LazyInternalContext.InitializeContext()
at System.Data.Entity.Internal.LazyInternalContext.GetObjectContextWithoutDatabaseInitialization()
at System.Data.Entity.Internal.InternalContext.UpdateEntitySetMappingsForType(Type entityType)
at System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType)
at System.Data.Entity.Internal.Linq.InternalSet`1.Initialize()
at System.Data.Entity.Internal.Linq.InternalSet`1.Include(String path)
at System.Data.Entity.Infrastructure.DbQuery`1.Include(String path)
at Clubr.WebJobs.ClubListingSchedule.Services.GuestQuestionReminderService.<SendReminders>d__1.MoveNext() in C:\sourcecode\clbr\Source\Clubr.WebJobs.ClubListingSchedule\Services\GuestQuestionReminderService.cs:line 24at System.Data.Entity.Internal.LazyInternalContext.InitializeContext()
at System.Data.Entity.Internal.LazyInternalContext.GetObjectContextWithoutDatabaseInitialization()
at System.Data.Entity.Internal.InternalContext.UpdateEntitySetMappingsForType(Type entityType)
at System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType)
at System.Data.Entity.Internal.Linq.InternalSet`1.Initialize()
at System.Data.Entity.Internal.Linq.InternalSet`1.Include(String path)
at System.Data.Entity.Infrastructure.DbQuery`1.Include(String path)
at Clubr.WebJobs.ClubListingSchedule.Services.GuestQuestionReminderService.<SendReminders>d__1.MoveNext() in C:\sourcecode\clbr\Source\Clubr.WebJobs.ClubListingSchedule\Services\GuestQuestionReminderService.cs:line 24     at System.Data.Entity.Internal.LazyInternalContext.InitializeContext()
at System.Data.Entity.Internal.LazyInternalContext.GetObjectContextWithoutDatabaseInitialization()
at System.Data.Entity.Internal.InternalContext.UpdateEntitySetMappingsForType(Type entityType)
at System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType)
at System.Data.Entity.Internal.Linq.InternalSet`1.Initialize()
at System.Data.Entity.Internal.Linq.InternalSet`1.Include(String path)
at System.Data.Entity.Infrastructure.DbQuery`1.Include(String path)
at Clubr.WebJobs.ClubListingSchedule.Services.GuestQuestionReminderService.<SendReminders>d__1.MoveNext() in C:\sourcecode\clbr\Source\Clubr.WebJobs.ClubListingSchedule\Services\GuestQuestionReminderService.cs:line 24

And the BaseService code -

public class BaseReminderService
{
    protected static IPushNotificationService NotificationService;
    protected static ILoggerService LoggerService;
    protected static ISMSService SmsService;
    protected static ClubrContext DbContext;

    public BaseReminderService(IPushNotificationService notificationService, ILoggerService loggerService, ClubrContext dbContext,
        ISMSService smsService)
    {
        NotificationService = notificationService;
        LoggerService = loggerService;
        DbContext = dbContext;
        SmsService = smsService;
    }
}`

Now looking at the code for BaseService, it seems the problem is because of the use of static variable!

I'm keeping question open so I know I'm thinking correct. (Plus if you can answer, since it's a static variable, whether it's shared among-st multiple processes/threads which may run in parallel!

Hiren Desai
  • 941
  • 1
  • 9
  • 33
  • https://stackoverflow.com/questions/21212822/the-operation-cannot-be-completed-because-the-dbcontext-has-been-disposed-using – Alberto Morillo May 28 '18 at 14:47
  • https://stackoverflow.com/questions/18635508/dbcontext-has-been-disposed – Alberto Morillo May 28 '18 at 14:48
  • where do you actually access the context db in that function? Where is "DbContext" coming from? – DevilSuichiro May 28 '18 at 14:56
  • @DevilSuichiro - Sorry, that is passed as parameter to function. See updated code – Hiren Desai May 29 '18 at 03:40
  • why is DbContext static then if it's passed in constructor? All other elements also seem like they belong to one instance, too. I don't know how static DbContext just being overridden at runtime over and over will behave, but accessing a disposed instance seems like the smallest problem you may run into. – DevilSuichiro May 29 '18 at 06:13
  • Yep,The code was written by someone and I was looking at exceptions and was trying to identify what's wrong with code. But as it seemed it's because of Static variable. – Hiren Desai May 29 '18 at 06:34
  • @HirenDesai can you please describe why dbcontext is static here? – programtreasures May 29 '18 at 07:47
  • @programtreasures - I have no idea why! As I mentioned earlier, the code is written by someone else. I was looking at the exception and was wondering what could have caused the exception and "Static" is the only case possible here because of which this error is occurring! – Hiren Desai May 29 '18 at 09:53

0 Answers0