title: Proper disposal of repository object inside controller
body: <p>I am having a hard time figuring this out. I have implemented Repository and Unit of Work patterns as a data access abstraction for my database. I am using Dependency Injection to inject them into the controller. The problem is when the controller is disposed, it disposes the repository, but then when I refresh the page, DbContext object inside repository is null (it shouldn't be, I think). The implementation of classes is shown below.</p>
  
  <p>This is the database Repository class:</p>
  
  <pre><code>public class ConferenceCrawlyDbRepository : IConferenceCrawlyDbRepository
  {
      private ConferenceCrawlyDbContext _context = null;
      private static ConferenceCrawlyDbRepository _instance = null;
  
      public IRepository&lt;AcademicDegree&gt; AcademicDegrees { get; private set; }
  
      public IRepository&lt;Conference&gt; Conferences { get; private set; }
  
      public IRepository&lt;ConferenceComment&gt; ConferenceComments { get; private set; }
  
      public IRepository&lt;ConferenceRating&gt; ConferenceRatings { get; private set; }
  
      public IRepository&lt;ConnectionConferenceRecommendation&gt; ConnectionConferenceRecommendation { get; private set; }
  
      public IRepository&lt;Country&gt; Countries { get; private set; }
  
      public IRepository&lt;ImportantDate&gt; ImportantDates { get; private set; }
  
      public IRepository&lt;Topic&gt; Topics { get; private set; }
  
      public IRepository&lt;UserProfile&gt; UserProfiles { get; private set; }
  
      public IRepository&lt;UserProfileSettings&gt; UserProfileSettings { get; private set; }
  
      public IRepository&lt;UsersConnection&gt; UserConnections { get; private set; }
  
      public IRepository&lt;Venue&gt; Venues { get; private set; }
  
      private ConferenceCrawlyDbRepository(ConferenceCrawlyDbContext context)
      {
          _context = context;
  
          AcademicDegrees = new Repository&lt;AcademicDegree&gt;(context);
          Conferences = new Repository&lt;Conference&gt;(context);
          ConferenceComments = new Repository&lt;ConferenceComment&gt;(context);
          ConferenceRatings = new Repository&lt;ConferenceRating&gt;(context);
          ConnectionConferenceRecommendation = new Repository&lt;ConnectionConferenceRecommendation&gt;(context);
          Countries = new Repository&lt;Country&gt;(context);
          ImportantDates = new Repository&lt;ImportantDate&gt;(context);
          Topics = new Repository&lt;Topic&gt;(context);
          UserProfiles = new Repository&lt;UserProfile&gt;(context);
          UserProfileSettings = new Repository&lt;UserProfileSettings&gt;(context);
          UserConnections = new Repository&lt;UsersConnection&gt;(context);
          Venues = new Repository&lt;Venue&gt;(context);
      }
  
      public static ConferenceCrawlyDbRepository Instance
      {
          get
          {
              if (_instance == null)
                  _instance = new ConferenceCrawlyDbRepository(new ConferenceCrawlyDbContext());
  
              return _instance;
          }
      }
  
      public bool CommitChanges()
      {
          try
          {
              return _context.SaveChanges() &gt; 0;
          }
          catch
          {
              // TODO: Add logging
              return false;
          }
      }
  
      public void Dispose()
      {
          if (_context != null)
              _context.Dispose();
      }
  </code></pre>
  
  <p>And this is the generic repository class:</p>
  
  <pre><code>public class Repository&lt;TEntity&gt; : IRepository&lt;TEntity&gt; where TEntity : class
  {
      private ConferenceCrawlyDbContext _context = null;
      private DbSet&lt;TEntity&gt; _dbSet = null;
  
      public Repository(ConferenceCrawlyDbContext context)
      {
          _context = context;
          _dbSet = context.Set&lt;TEntity&gt;();
      }
  
      public DbSet&lt;TEntity&gt; DbSet
      {
          get
          {
              return _dbSet;
          }
      }
  
      public bool Add(TEntity entity)
      {
          try
          {
              DbSet.Add(entity);
  
              return true;
          }
          catch (Exception ex)
          {
              // TODO: Add logging
              return false;
          }
  
      }
  
      public bool Update(TEntity entity)
      {
          try
          {
              var entry = _context.Entry&lt;TEntity&gt;(entity);
  
              DbSet.Attach(entity);
  
              entry.State = EntityState.Modified;
  
              return true;
          }
          catch(Exception ex)
          {
              // TODO: Add logging
              return false;
          }
      }
  
      public bool Remove(TEntity entity)
      {
          try
          {
              DbSet.Remove(entity);
  
              return true;
          }
          catch (Exception ex)
          {
              // TODO: Add logging
              return false;
          }
      }
  
      public IQueryable&lt;TEntity&gt; GetAll()
      {
          return DbSet;
      }
  
      public IQueryable&lt;TEntity&gt; Find(Expression&lt;Func&lt;TEntity, bool&gt;&gt; predicate)
      {
          return DbSet.Where(predicate);
      }
  
      public TEntity FindById(params object[] keys)
      {
          return DbSet.Find(keys);
      }
  
      public bool Contains(Expression&lt;Func&lt;TEntity, bool&gt;&gt; predicate)
      {
          return _dbSet.Any(predicate);
      }
  
      public bool CommitChanges()
      {
          try
          {
              return _context.SaveChanges() &gt; 0;
          }
          catch
          {
              // TODO: Add logging
              return false;
          }
      }
  
      public void Dispose()
      {
          if (_context != null)
              _context.Dispose();
      }
  }
  </code></pre>
  
  <p>Here is my custom controller factory for dependency injection:</p>
  
  <pre><code>    public class CustomControllerFactory : DefaultControllerFactory
      {
          protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
          {
              if (controllerType != null)
              {
                  if (controllerType.GetConstructor(new Type[] { typeof(IConferenceCrawlyDbRepository) }) != null)
                      return Activator.CreateInstance(controllerType, new object[] { ConferenceCrawlyDbRepository.Instance }) as Controller;
                  else if (controllerType.GetConstructor(new Type[] { typeof(IConferenceCrawlyDbRepository), typeof(IMailService) }) != null)
                      return Activator.CreateInstance(controllerType, new object[] { ConferenceCrawlyDbRepository.Instance,
  #if DEBUG
                       MockMailService.Instance
  #else
                       MailService.Instance
  #endif
                       }) as Controller;
              }
  
              return base.GetControllerInstance(requestContext, controllerType);
          }
  </code></pre>
  
  <p>And finally, controller with its action:</p>
  
  <pre><code>public class HomeController : Controller
      {
          private IConferenceCrawlyDbRepository _dbRepository;
          private IMailService _mailService;
  
          public HomeController(IConferenceCrawlyDbRepository dbRepository, IMailService mailService)
          {
              _dbRepository = dbRepository;
              _mailService = mailService;
          }
  
          //
          // GET: /
          public ActionResult Index()
          {
              var countries = _dbRepository.Countries.GetAll().ToList();
  
              return View(countries);
          }
  
          //
          // GET: /Home/About
          public ActionResult About()
          {
              return View();
          }
  
          //
          // GET: /Home/Contact
          public ActionResult Contact()
          {
              return View(new Contact());
          }
  
          //
          // POST: /Home/Contact
          [HttpPost]
          [ValidateAntiForgeryToken]
          public async Task&lt;ActionResult&gt; Contact(Contact contact)
          {
              if (ModelState.IsValid)
              {
                  if (await _mailService.SendMail(contact.Email, contact.Title,
                      String.Format("{1}{0}{2}", Environment.NewLine, contact.Message, String.IsNullOrEmpty(contact.Name) ? "Anonimous" : contact.Name)))
                  {
                      ViewBag.SuccessMessage = "Comment has been successfully sent.";
  
                      return View(new Contact());
                  }
                  else
                      ViewBag.ErrorMessage = "Couldn't send your email. Please try again later";
              }
  
              return View(contact);
          }
  
          protected override void Dispose(bool disposing)
          {
              if (_dbRepository != null)
                  _dbRepository.Dispose();
  
              base.Dispose(disposing);
          }
      }
  </code></pre>
  
  <p>The Exception is thrown inside index action when I call the repository, but only after the first time accessing this controller and it says that DbContext object inside repository. I am obviously doing something wrong, but I can't figure it out.</p>