Search code examples
c#entity-frameworkdispose

Using IDisposable causes error: "An object reference is required for the non-static field, method, or property"


This error message usually means that an instance property is being accessed from a static method. But in my case, none of the methods are static. If I remove the ":IDisposable" and the Dispose method, the error message goes away. But I want to be able to clean up database resources when I am done using the DbOps object. Why is this error occurring?

using System.Data.Entity;

namespace DbAccess
{
    class DbAccess
    {
        public void PerformSomeWork()
        {
            using (DbOps dbOperations = new DbOps())
            {
                List<Person> people = DbOps.GetPeople();
                // ... other database access
            }

        }
    }

    class DbOps : IDisposable
    {
        CustomerContext customerContext;

        public DbOps()
        {
            customerContext = new CustomerContext();
        }

        public void Dispose()
        {
            customerContext.Dispose();
        }

        public List<Person> GetPeople()
        {
            return customerContext.People.ToList();
            // return new List<Category>();
        }

        // other database operations
    }

    class CustomerContext : DbContext
    {
        public DbSet<Person> People { get; set; }
        // other DbSets
    }

    class Person
    {
        string name;
    }

}

Solution

  • Seems like

    using (DbOps dbOperations = new DbOps())
    {
        List<Person> people = DbOps.GetPeople();
    }
    

    should be

    using (DbOps dbOperations = new DbOps())
    {
        List<Person> people = dbOperations.GetPeople();
    }
    

    IDisposable doesn't seem to be related but I imagine that when you remove the IDisposable you also change these lines since you can't have using without Dispose.