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:
Is abstracting the context possible and if so is it a good practice to do. My biggest concern is disposal.
Normally, StatContext would be a private variable, but I can't return that. How can I keep StatContext private?
Thanks
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.