Search code examples
c#interfaceentity-framework-6abstraction

Abstracting a dbContext into a separate class - Entity Framework 6


I want to be able to abstract my EF6 context so that it is created once and used by multiple classes. The code as follows:

Interface:

public interface IInterface<T>
{
    IEnumerable<T> ExecStoredProc(string x, DateTime date,
             int y, string  statistics );
}

Context class:

public class Context
{
    public readonly StatisticsEntities StatContext;

    public static StatisticsRepo(StatisticsEntities statContext)
    {
        StatContext = statContext;
        return StatContext;
    }
}

Class that calls Context class:

public class Class2: Iinterface<Class2Type>
{
    var returnContext = context.StatisticsEntities();

    public IEnumerable<Class2Type> ExecStoredProc(string x, DateTime date,
            int y, string  statistics )
           {
              return returnContext.ExecMethod_Select(x,date,y,statistics).AsEnumerable();
           }

}

The following are my questions:

  1. Is abstracting the context possible and if so is it a good practice to do. My biggest concern is disposal.

  2. Normally, StatContext would be a private variable, but I can't return that. How can I keep StatContext private?

Thanks


Solution

  • I took a different approach and used property injection:

    public class Context
        {
            //Property Injection to be used for all repo classes
            private StatisticsEntities _statContext = new StatisticsEntities();
            public StatisticsEntities StatContext { get; set; }
        }
    

    Then I added a try catch finally block in the calling class to dispose of the context.